Advertisement
willtrieagain

Untitled

Oct 10th, 2020
48
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.01 KB | None | 0 0
  1. #include<stdio.h>
  2. #include<pthread.h>
  3. #include<stdlib.h>
  4. #include<unistd.h>
  5.  
  6. int var;
  7. pthread_mutext_t mutex;
  8.  
  9. typedef struct s {
  10. int id;
  11. } s;
  12.  
  13. void* t(void *inp) {
  14. s* inputs = (s*) inp;
  15.  
  16. sleep(2);
  17.  
  18. pthread_mutext_lock(&mutex);
  19. if (var == 0) {
  20. printf("Child %d didn't eat\n", inputs->id);
  21. else {
  22. printf("Child %d ate\n", inputs->id);
  23. var--;
  24. }
  25. pthread_mutext_unlock(&mutex);
  26. return NULL;
  27. }
  28.  
  29. int main() {
  30. var = 1;
  31. printf("Total cookies: %d\n", var);
  32.  
  33. pthread_t tid1;
  34. pthread_t tid2;
  35.  
  36. s* thread1_input = (s*)malloc(sizeof(s));
  37. s* thread2_input = (s*)malloc(sizeof(s));
  38. thread1_input->id = 1;
  39. thread2_input->id = 2;
  40.  
  41. pthread_mutext_init(&mutex, NULL);
  42.  
  43. pthread_create(&tid1, NULL, t, (void*)(thread1_input));
  44. pthread_create(&tid2, NULL, t, (void*)(thread2_input));
  45.  
  46. pthread_join(tid1, NULL);
  47. pthread_join(tid2, NULL);
  48.  
  49. pthread_mutex_destroy(&mutex);
  50. printf("%d\n", var);
  51. return 0;
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement