fork(1) download
  1. #include <stdio.h>
  2. #include <pthread.h>
  3. #include <semaphore.h>
  4. sem_t odd_sem, even_sem;
  5. int limit;
  6. void* print_odd(void* arg)
  7. {
  8. for(int i = 1; i <= limit; i += 2)
  9. {
  10. sem_wait(&odd_sem);
  11. printf("%d ", i);
  12. sem_post(&even_sem);
  13. }
  14. return NULL;
  15. }
  16. void* print_even(void* arg)
  17. {
  18. for(int i = 2; i <= limit; i += 2)
  19. {
  20. sem_wait(&even_sem);
  21. printf("%d ", i);
  22. sem_post(&odd_sem);
  23. }
  24. return NULL;
  25. }
  26. int main()
  27. {
  28. pthread_t t1, t2;
  29. printf("Enter limit: ");
  30. scanf("%d", &limit);
  31. sem_init(&odd_sem, 0, 1);
  32. sem_init(&even_sem, 0, 0);
  33. pthread_create(&t1, NULL, print_odd, NULL);
  34. pthread_create(&t2, NULL, print_even, NULL);
  35. pthread_join(t1, NULL);
  36. pthread_join(t2, NULL);
  37. sem_destroy(&odd_sem);
  38. sem_destroy(&even_sem);
  39.  
  40. return 0;
  41. }
Success #stdin #stdout 0.01s 5288KB
stdin
14
stdout
Enter limit: 1 2 3 4 5 6 7 8 9 10 11 12 13 14