fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <pthread.h>
  4. #include <semaphore.h>
  5. #include <unistd.h>
  6.  
  7. #define max_ports 3
  8. #define num_threads 6
  9.  
  10. sem_t portsemaphore;
  11.  
  12.  
  13. void* open_port(void *thread_id) {
  14. int tid = *((int *)thread_id);
  15.  
  16. printf("Thread %d: waiting to open port...\n", tid);
  17.  
  18. sem_wait(&portsemaphore);
  19. printf("Thread %d: PORT OPENED\n", tid);
  20.  
  21. sleep(2);
  22.  
  23. printf("Thread %d: closing port.\n", tid);
  24. sem_post(&portsemaphore);
  25.  
  26. return NULL;
  27. }
  28.  
  29. int main() {
  30. pthread_t threads[num_threads];
  31. int thread_ids[num_threads];
  32.  
  33.  
  34. sem_init(&portsemaphore, 0, max_ports);
  35.  
  36. for(int i = 0; i < num_threads; i++) {
  37. thread_ids[i] = i + 1;
  38.  
  39. pthread_create(&threads[i], NULL, open_port, &thread_ids[i]);
  40.  
  41. }
  42.  
  43.  
  44. for(int i = 0; i < num_threads; i++) {
  45. pthread_join(threads[i], NULL);
  46. }
  47.  
  48. sem_destroy(&portsemaphore);
  49. printf("All threads finished.\n");
  50. return 0;
  51. }
  52.  
Success #stdin #stdout 0s 5316KB
stdin
Standard input is empty
stdout
Thread 6: waiting to open port...
Thread 6: PORT OPENED
Thread 5: waiting to open port...
Thread 5: PORT OPENED
Thread 4: waiting to open port...
Thread 4: PORT OPENED
Thread 3: waiting to open port...
Thread 2: waiting to open port...
Thread 1: waiting to open port...
Thread 6: closing port.
Thread 5: closing port.
Thread 4: closing port.
Thread 3: PORT OPENED
Thread 2: PORT OPENED
Thread 1: PORT OPENED
Thread 3: closing port.
Thread 2: closing port.
Thread 1: closing port.
All threads finished.