Advertisement
Guest User

Untitled

a guest
Apr 10th, 2020
160
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.26 KB | None | 0 0
  1. #include<stdio.h>
  2. #define HAVE_STRUCT_TIMESPEC
  3. #include<pthread.h>
  4.  
  5. pthread_t tid[2];
  6. unsigned int shared_data = 0;
  7.  
  8. pthread_mutex_t mutex;
  9. unsigned int rc;
  10. //prototypes for callback functions
  11.  
  12. void* PrintEvenNumbers(void*);
  13. void* PrintOddNumbers(void*);
  14.  
  15. void main(void)
  16. {
  17.     pthread_create(&tid[0], 0, &PrintEvenNumbers, 0);
  18.     pthread_create(&tid[1], 0, &PrintOddNumbers, 0);
  19.     sleep(3);
  20.  
  21.     pthread_join(tid[0], NULL);
  22.     pthread_join(tid[1], NULL);
  23. }
  24.  
  25. void* PrintEvenNumbers(void* ptr)
  26. {
  27.     rc = pthread_mutex_lock(&mutex);
  28.  
  29.     do
  30.     {
  31.         if (shared_data % 2 == 0)
  32.         {
  33.             printf("Even:%d\n", shared_data);
  34.             shared_data++;
  35.         }
  36.         else
  37.         {
  38.             rc = pthread_mutex_unlock(&mutex); //if number is odd, do not print, release mutex
  39.         }
  40.     }
  41.     while (shared_data <= 10);
  42. }
  43.  
  44. void* PrintOddNumbers(void* ptr1)
  45. {
  46.     rc = pthread_mutex_lock(&mutex);
  47.  
  48.     do
  49.     {
  50.         if (shared_data % 2 != 0)
  51.         {
  52.             printf("Odd:%d\n", shared_data);
  53.             shared_data++;
  54.         }
  55.         else
  56.         {
  57.             rc = pthread_mutex_unlock(&mutex); //if number is even, do not print, release mutex
  58.         }
  59.     }
  60.     while (shared_data <= 10);
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement