fork download
  1.  
  2. #include <stdio.h>
  3. #include <pthread.h>
  4.  
  5. #define MAX_NUM 50
  6.  
  7. int number = 1;
  8. pthread_mutex_t lock;
  9. pthread_cond_t cond;
  10. int turn = 0; // 0, 1, 2 for three threads
  11.  
  12. void* print_numbers(void* arg) {
  13. int thread_id = *(int*)arg;
  14.  
  15. while (1) {
  16. pthread_mutex_lock(&lock);
  17.  
  18. while (turn != thread_id && number <= MAX_NUM) {
  19. pthread_cond_wait(&cond, &lock);
  20. }
  21.  
  22. if (number > MAX_NUM) {
  23. pthread_cond_broadcast(&cond);
  24. pthread_mutex_unlock(&lock);
  25. break;
  26. }
  27.  
  28. printf("Thread %d: %d\n", thread_id + 1, number);
  29. number++;
  30. turn = (turn + 1) % 3;
  31.  
  32. pthread_cond_broadcast(&cond);
  33. pthread_mutex_unlock(&lock);
  34. }
  35.  
  36. return NULL;
  37. }
  38.  
  39. int main() {
  40. pthread_t threads[3];
  41. int ids[3] = {0, 1, 2};
  42.  
  43. pthread_mutex_init(&lock, NULL);
  44. pthread_cond_init(&cond, NULL);
  45.  
  46. for (int i = 0; i < 3; i++) {
  47. pthread_create(&threads[i], NULL, print_numbers, &ids[i]);
  48. }
  49.  
  50. for (int i = 0; i < 3; i++) {
  51. pthread_join(threads[i], NULL);
  52. }
  53.  
  54. pthread_mutex_destroy(&lock);
  55. pthread_cond_destroy(&cond);
  56.  
  57. return 0;
  58. }
  59.  
Success #stdin #stdout 0.01s 5272KB
stdin
Standard input is empty
stdout
Thread 1: 1
Thread 2: 2
Thread 3: 3
Thread 1: 4
Thread 2: 5
Thread 3: 6
Thread 1: 7
Thread 2: 8
Thread 3: 9
Thread 1: 10
Thread 2: 11
Thread 3: 12
Thread 1: 13
Thread 2: 14
Thread 3: 15
Thread 1: 16
Thread 2: 17
Thread 3: 18
Thread 1: 19
Thread 2: 20
Thread 3: 21
Thread 1: 22
Thread 2: 23
Thread 3: 24
Thread 1: 25
Thread 2: 26
Thread 3: 27
Thread 1: 28
Thread 2: 29
Thread 3: 30
Thread 1: 31
Thread 2: 32
Thread 3: 33
Thread 1: 34
Thread 2: 35
Thread 3: 36
Thread 1: 37
Thread 2: 38
Thread 3: 39
Thread 1: 40
Thread 2: 41
Thread 3: 42
Thread 1: 43
Thread 2: 44
Thread 3: 45
Thread 1: 46
Thread 2: 47
Thread 3: 48
Thread 1: 49
Thread 2: 50