fork download
  1. #include <pthread.h>
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <unistd.h>
  5. #include <string.h>
  6. #include <semaphore.h>
  7.  
  8. #define THREAD_NUM 4
  9.  
  10. sem_t semaphore;
  11.  
  12. void* routine(void* args) {
  13. sem_wait(&semaphore);
  14. sleep(1);
  15. printf("Hello from thread %d\n", *(int*)args);
  16. sem_post(&semaphore);
  17. free(args);
  18. }
  19.  
  20. int main(int argc, char *argv[]) {
  21. pthread_t th[THREAD_NUM];
  22. sem_init(&semaphore, 0, 4);
  23. int i;
  24. for (i = 0; i < THREAD_NUM; i++) {
  25. int* a = malloc(sizeof(int));
  26. *a = i;
  27. if (pthread_create(&th[i], NULL, &routine, a) != 0) {
  28. perror("Failed to create thread");
  29. }
  30. }
  31.  
  32. for (i = 0; i < THREAD_NUM; i++) {
  33. if (pthread_join(th[i], NULL) != 0) {
  34. perror("Failed to join thread");
  35. }
  36. }
  37. sem_destroy(&semaphore);
  38. return 0;
  39. }
Success #stdin #stdout 0.01s 5284KB
stdin
Standard input is empty
stdout
Hello from thread 3
Hello from thread 2
Hello from thread 1
Hello from thread 0