Advertisement
unstoppable7

Untitled

Feb 5th, 2023
729
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.85 KB | None | 0 0
  1. #include <pthread.h>
  2. #include <semaphore.h>
  3. #include <stdio.h>
  4. #include <stdlib.h>
  5.  
  6. #define NUM_THREADS 5
  7. sem_t semaphore;
  8.  
  9. void *worker_thread(void *arg) {
  10.   int thread_num = *((int*) arg);
  11.   printf("Thread %d waiting on semaphore...\n", thread_num);
  12.   sem_wait(&semaphore);
  13.   printf("Thread %d enters critical section...\n", thread_num);
  14.   // Acción crítica
  15.   printf("Thread %d exits critical section...\n", thread_num);
  16.   sem_post(&semaphore);
  17.   return NULL;
  18. }
  19.  
  20. int main() {
  21.   pthread_t threads[NUM_THREADS];
  22.   int thread_args[NUM_THREADS];
  23.   sem_init(&semaphore, 0, 1);
  24.   for (int i = 0; i < NUM_THREADS; ++i) {
  25.     thread_args[i] = i;
  26.     pthread_create(&threads[i], NULL, worker_thread, &thread_args[i]);
  27.   }
  28.   for (int i = 0; i < NUM_THREADS; ++i) {
  29.     pthread_join(threads[i], NULL);
  30.   }
  31.   sem_destroy(&semaphore);
  32.   return 0;
  33. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement