Guest User

Untitled

a guest
May 30th, 2015
616
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.49 KB | None | 0 0
  1. #include <pthread.h>
  2. #include <stdlib.h>
  3. #include <stdio.h>
  4.  
  5. #define M 100000000
  6. #define N 1
  7.  
  8. static int count = 0;
  9. static int *res;
  10.  
  11. static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
  12. static pthread_mutex_t lock2 = PTHREAD_MUTEX_INITIALIZER;
  13.  
  14. static int do_calc (int x)
  15. {
  16.     int res;
  17.  
  18.     res = x ^ (x >> 16);
  19.     res *= 0xcafebabe;
  20.     res = res ^ (x >> 8);
  21.     res *= 0xfeedabba;
  22.     return res;
  23. }
  24.  
  25. #if 1
  26. void* start (void *arg)
  27. {
  28.     int count_old;
  29.     while (1)
  30.     {
  31.         count_old = __sync_add_and_fetch (&count, 1);
  32.         if (count_old >= M) break;
  33.         res[count_old] = do_calc(count_old);
  34.     }
  35.     return NULL;
  36. }
  37. #else
  38. void* start (void *arg)
  39. {
  40.     int count_old, val;
  41.     while (1)
  42.     {
  43.         pthread_mutex_lock (&lock);
  44.         count_old = count++;
  45.         pthread_mutex_unlock (&lock);
  46.  
  47.         if (count_old >= M) break;
  48.         val = do_calc (count_old);
  49.  
  50.         pthread_mutex_lock (&lock2);
  51.         res[count_old] = val;
  52.         pthread_mutex_unlock (&lock2);
  53.     }
  54.     return NULL;
  55. }
  56. #endif
  57.  
  58. int main ()
  59. {
  60.     int i;
  61.     pthread_t threads[N];
  62.     res = malloc (sizeof(int)*M);
  63.  
  64.     //start(NULL);
  65.     for (i = 0; i < N; i++)
  66.         pthread_create (&(threads[i]), NULL, start, NULL);
  67.     for (i = 0; i < N; i++)
  68.         pthread_join (threads[i], NULL);
  69.  
  70.     printf ("%i\n", count);
  71.     for (i=0; i<M; i++)
  72.         if (do_calc(i) != res[i]) printf ("%i %i\n", do_calc(i), res[i]);
  73.     free (res);
  74.  
  75.     return 0;
  76. }
Advertisement
Add Comment
Please, Sign In to add comment