01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 | #include <unistd.h> #include <stdlib.h> #include <stdio.h> #include <pthread.h> #define wmb() __asm__ __volatile ("sfence":::) unsigned int a = 0; unsigned int b = 1; pthread_mutex_t lock; static void * f( void * arg) { unsigned int c,d; for (;;){ c = a; //wmb(); d = b; if (c>=d) { printf ( "c=%x d=%x\n" ,c,d); return NULL; } } } static void * g( void * arg) { for (;;){ pthread_mutex_lock (&lock); b++; a++; if (b == 0x7fffffff) { b = 1; a = 0; } pthread_mutex_unlock (&lock); } } int main( int argc, const char * argv[]) { pthread_t pid1,pid2; pthread_mutex_init (&lock, NULL); if (pthread_create(&pid1, 0, f, 0)){ printf ( "Create thread1 error\n" ); exit (-1); } if (pthread_create(&pid2, 0, g, 0)){ printf ( "Create thread2 error\n" ); exit (-1); } while (1) sleep(1); return 0; } |
联系客服