//compile me with gcc pthread.cc -o pthread -lpthread #include #include #include int num; //global variables visible to both threads //declare and initialize mutex lock (global variable) pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; void *procedure( void *); main() { int id1 = 0; int id2 = 1; //a thread pthread_t thread; //pthread_t thread2; // Before you create the new thread, init mutex pthread_mutex_init(&mutex, NULL); //this call creates a thread that starts execution at procedure and takes id1 as argument pthread_create(&thread, NULL, procedure, (void *) &id1); //the original thread calls procedure as well with id2 as argument procedure(&id2); //or we could create another thread that calls it //pthread_create(&thread2, NULL, procedure, (void *) &id2); //wait for other thread to finish pthread_join(thread,NULL); pthread_mutex_destroy(&mutex); } void *procedure(void *arg) { int threadid = * ((int *)arg); printf("Thread %d reporting to duty, Sir!\n",threadid); //we use mutex before accessing the shared num variable. Try your code with and without the mutex commands pthread_mutex_lock(&mutex); num++; printf("Number was %d, Sir!\n",num); //dont forget to unlock to let the other thread in pthread_mutex_unlock(&mutex); }