Advertisement
Guest User

Untitled

a guest
Oct 24th, 2017
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.11 KB | None | 0 0
  1. #include <stdlib.h>
  2. #include <stdio.h>
  3. #include <pthread.h>
  4.  
  5. static pthread_mutex_t cs_mutex;
  6.  
  7. typedef struct {
  8.   int c;
  9.   int *red;
  10. } st;
  11.  
  12. void* print(void *pParam) {
  13.     int c = ((st*)pParam)->c;
  14.     int *red = ((st*)pParam)->red;
  15.     int i;
  16.  
  17.     for(i = 0; i < 1000; i++) {
  18.       int b = 0;
  19.       while (!b) {
  20.           pthread_mutex_lock(&cs_mutex);
  21.           b = (*red == c);
  22.           pthread_mutex_unlock(&cs_mutex);
  23.       };
  24.       pthread_mutex_lock(&cs_mutex);
  25.       printf("%d", c + 1);
  26.       fflush(stdout);
  27.       *red = (*red + 1) % 3;
  28.       pthread_mutex_unlock(&cs_mutex);
  29.     }
  30.  
  31.     return 0;
  32. }
  33.  
  34. int main(void) {
  35.     pthread_t hPrint1;
  36.     pthread_t hPrint2;
  37.     pthread_t hPrint3;
  38.  
  39.     pthread_mutex_init(&cs_mutex, NULL);
  40.  
  41.     st str[3];
  42.    
  43.     int red = 0;
  44.  
  45.     int i;
  46.     for (i = 0; i < 3; i++) {
  47.       str[i].c = i;
  48.       str[i].red = &red;
  49.     }
  50.  
  51.     pthread_create(&hPrint1, NULL, print, (void*)&str[0]);
  52.     pthread_create(&hPrint2, NULL, print, (void*)&str[1]);
  53.     pthread_create(&hPrint3, NULL, print, (void*)&str[2]);
  54.  
  55.     getchar();
  56.  
  57.     return 0;
  58. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement