Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <pthread.h>
- #include <stdlib.h>
- #include <stdio.h>
- #define M 100000000
- #define N 1
- static int count = 0;
- static int *res;
- static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
- static pthread_mutex_t lock2 = PTHREAD_MUTEX_INITIALIZER;
- static int do_calc (int x)
- {
- int res;
- res = x ^ (x >> 16);
- res *= 0xcafebabe;
- res = res ^ (x >> 8);
- res *= 0xfeedabba;
- return res;
- }
- #if 1
- void* start (void *arg)
- {
- int count_old;
- while (1)
- {
- count_old = __sync_add_and_fetch (&count, 1);
- if (count_old >= M) break;
- res[count_old] = do_calc(count_old);
- }
- return NULL;
- }
- #else
- void* start (void *arg)
- {
- int count_old, val;
- while (1)
- {
- pthread_mutex_lock (&lock);
- count_old = count++;
- pthread_mutex_unlock (&lock);
- if (count_old >= M) break;
- val = do_calc (count_old);
- pthread_mutex_lock (&lock2);
- res[count_old] = val;
- pthread_mutex_unlock (&lock2);
- }
- return NULL;
- }
- #endif
- int main ()
- {
- int i;
- pthread_t threads[N];
- res = malloc (sizeof(int)*M);
- //start(NULL);
- for (i = 0; i < N; i++)
- pthread_create (&(threads[i]), NULL, start, NULL);
- for (i = 0; i < N; i++)
- pthread_join (threads[i], NULL);
- printf ("%i\n", count);
- for (i=0; i<M; i++)
- if (do_calc(i) != res[i]) printf ("%i %i\n", do_calc(i), res[i]);
- free (res);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment