I want to create a program where there are 2 threads reader and writer.
Both reader and writer runs for 10 iterations.
I need a synchronization mechanism that can enable reader and writer execute alternatively.
I tried only with mutex but it did not work. So I used conditional wait, still I could not achieve the results and the code is in infinite wait state. Below is the code that I tried.
int my_global = 0;
int write_flag = 0;
pthread_mutex_t mutex;
pthread_cond_t mycond;
void *reader() {
for(int j=0;j<10;j++){
pthread_mutex_lock(&mutex);
printf("\nReader - value of global is %d & write flag is %d and j is %d",my_global,write_flag,j);
write_flag = 1;
pthread_mutex_unlock(&mutex);
pthread_cond_signal(&mycond);
// sleep(1);
}
}
void *writer(){
for(int k=0;k<10;k++){
pthread_mutex_lock(&mutex);
printf("\nstarted writer");
while(write_flag!=1){
pthread_cond_wait(&mycond,&mutex);
}
write_flag = 0;
my_global++;
printf("\nwriter done and writeflag is %d and global is %d and k is %d",write_flag,my_global,k);
pthread_mutex_unlock(&mutex);
}
}
int main()
{
pthread_t my_reader;
pthread_t my_writer;
pthread_cond_init(&mycond,NULL);
pthread_mutex_init(&mutex,NULL);
if (pthread_create(&my_reader, NULL, &reader, NULL) != 0) {
perror("Failed to create thread");
}
if (pthread_create(&my_writer, NULL, &writer, NULL) != 0) {
perror("Failed to create thread");
}
if (pthread_join(my_reader, NULL) != 0) {
perror("Failed to join thread");
}
if (pthread_join(my_writer, NULL) != 0) {
perror("Failed to join thread");
}
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&mycond);
return 0;
}
pthread_*functions don't seterrno, so your use ofperroris wrong. You should doif ( errno = pthread_foo( ... ) ) { perror( ... ); exit( 1 ); }void *reader() { }should bevoid *reader( void *arg ). You can use(void)arg;in the function to avoid warnings. Same forwriter.pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;to initialize a mutex in static storage instead of usingpthread_mutex_init. Similarly, you can usepthread_cond_t cond = PTHREAD_COND_INITIALIZER;to initialize a cond var in static storage instead of usingpthread_cond_init.