synchronization - How to use mutex to sync this secuence: (A or B)C (A or B) (A or B)C -


i'm learning sync mutex , have problem. need 3 threads, each 1 print letter , i've print secuence te tittle in infinite loop. idea , b thread make same thing except print. idea use trylock initial value 1, aorb mutex initial value 1 , c mutex initial value 0. realise work first iteration , write alway 2 (aorb)... posible solve in way?

void *ruta(){ //rut b same print b     while(1){         pthread_mutex_lock(&semaob);         printf("a");         fflush(stdout);         sleep(1);         if(sem_trywait(&turnoc) == 0){//(aorb)             pthread_mutex_unlock(&semc);         }else{////(aorb)(aorb)             sem_post(&turnoc);             pthread_mutex_unlock(&mutexaob);         }      }     pthread_exit(null); }   void *rutc(){     while(1){         pthread_mutex_lock(&mutexc);         printf("c");         sleep(1);         fflush(stdout);         pthread_mutex_unlock(&semaob);     }     pthread_exit(null);  } 

you can't unlock mutex in different thread 1 locked it.

you can solve problem either using sempahores, or using mutexes , condition variables - should not mix 2 approaches.

here's example of solving using mutex , condition variable pair:

int state = 0; pthread_mutex_t mutex = pthread_mutex_initializer; pthread_cond_t cond = pthread_cond_initializer;  void *runa(void *arg) {     while (1)     {         pthread_mutex_lock(&mutex);         while (state == 1 || state == 4)             pthread_cond_wait(&cond, &mutex);          putchar('a');         fflush(stdout);         if (++state > 4)             state = 0;         pthread_mutex_unlock(&mutex);          pthread_cond_broadcast(&cond);     }     return null; }  void *runb(void *arg) {     while (1)     {         pthread_mutex_lock(&mutex);         while (state == 1 || state == 4)             pthread_cond_wait(&cond, &mutex);          putchar('b');         fflush(stdout);         if (++state > 4)             state = 0;         pthread_mutex_unlock(&mutex);          pthread_cond_broadcast(&cond);     }     return null; }  void *runc(void *arg) {     while (1)     {         pthread_mutex_lock(&mutex);         while (state == 0 || state == 2 || state == 3)             pthread_cond_wait(&cond, &mutex);          putchar('c');         fflush(stdout);         if (++state > 4)             state = 0;         pthread_mutex_unlock(&mutex);          pthread_cond_broadcast(&cond);     }     return null; } 

Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -