/* pthread3.c Race condition $ g++ -Wall -lpthread pthread3.c++ $ ./a.out 500000 output: 0, +ve and -ve */ #include using namespace std; #include #include #include int times, n = 0 ; void * thread1(void *) ; void * thread2(void *) ; void inc() {n=n+1;} void dec() {n=n-1;} int main(int count, char *vect[]) { // argument is data for times pthread_t thID1, thID2; if(count < 2) { perror("No argument for times\n") ; exit(1) ; } times = atoi(vect[1]) ; pthread_create(&thID1, NULL, thread1, NULL) ; pthread_create(&thID2, NULL, thread2, NULL) ; pthread_join(thID1, NULL) ; pthread_join(thID2, NULL) ; cout << "n: " << n << "\n" ; return 0 ; } void *thread1(void *vp) { int i ; for(i=1; i<=times; ++i) inc(); return NULL ; } void *thread2(void *vp) { int i ; for(i=1; i<=times; ++i) dec() ; return NULL ; }