c - Thread synchronizing with mutex -


i have 2 threads. first 1 should write:

1 2 3 4 5 6 7 8 9 

second 1 should write:

am 1 2 3 4 5 6 7 8 9 

this code:

#include <pthread.h> #include <stdio.h> #include <stdlib.h>  pthread_mutex_t mutex;  int firstcounter = 0; int secondcounter = 0;  void *writeloop(void *arg) {     while(firstcounter < 10) {         pthread_mutex_lock(&mutex);         firstcounter++;         printf("%d\n", firstcounter);         pthread_mutex_unlock(&mutex);     }     exit(0); }  void *readloop(void *arg) {     while(secondcounter < 10) {         pthread_mutex_lock(&mutex);         secondcounter++;         printf("am %d\n", secondcounter);         pthread_mutex_unlock(&mutex);     }     exit(0); }  int main(void) {     pthread_t tid, fid;     pthread_mutex_init(&mutex, null);     pthread_create(&tid, null, writeloop, null);     pthread_create(&fid, null, readloop, null);     pthread_join(tid, null);     pthread_join(fid, null);     pthread_mutex_destroy(&mutex);     return 0; } 

but not working correctly. second method doesnt work, works. first 1 work correctly, prints:

1 2 3 4 5 6 7 

where mistake?

better use 2 different mutex variables handle 2 thread read , write operation.

since in current situation depends upon scheduling, if write thread gets schedule first acquire mutex lock. so, later read thread has wait mutex lock until write thread released , vice-versa.


Comments

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

thorough guide for profiling racket code -