Advertisement
daniv1

Untitled

Dec 4th, 2018
113
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.87 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <pthread.h>
  3.  
  4. pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
  5. pthread_cond_t cond =PTHREAD_COND_INITIALIZER;
  6.  
  7. int condition = 0;
  8.  
  9. void send_msg()
  10. {
  11.     condition = 1;
  12.     pthread_cond_broadcast(&cond);
  13. }
  14.  
  15. void resive_msg()
  16. {
  17.     pthread_mutex_lock(&mutex);
  18.     while(!condition)
  19.     {
  20.         pthread_cond_wait(&cond,&mutex);
  21.     }
  22.     pthread_mutex_unlock(&mutex);
  23. }
  24.  
  25. void *createThread(void *p)
  26. {
  27.     int threadID = *(int*)p;
  28.     printf("Thread %i is waiting for message ...\n",threadID);
  29.     resive_msg();
  30.     printf("Thread %i reseive the message ",threadID);
  31.  
  32. }
  33. int main()
  34. {
  35.     int thread_cnt = 10;
  36.     pthread_t threads[thread_cnt];
  37.     for(int i = 0 ; i < thread_cnt; ++i)
  38.     {
  39.         printf("thread %i is starting\n",i);
  40.         pthread_create(&threads[i],NULL,createThread,&i);
  41.     }
  42.     printf("Done\n");
  43. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement