Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <pthread.h>
- #include <semaphore.h>
- #include <stdio.h>
- #include <stdlib.h>
- #define NUM_THREADS 5
- sem_t semaphore;
- void *worker_thread(void *arg) {
- int thread_num = *((int*) arg);
- printf("Thread %d waiting on semaphore...\n", thread_num);
- sem_wait(&semaphore);
- printf("Thread %d enters critical section...\n", thread_num);
- // Acción crítica
- printf("Thread %d exits critical section...\n", thread_num);
- sem_post(&semaphore);
- return NULL;
- }
- int main() {
- pthread_t threads[NUM_THREADS];
- int thread_args[NUM_THREADS];
- sem_init(&semaphore, 0, 1);
- for (int i = 0; i < NUM_THREADS; ++i) {
- thread_args[i] = i;
- pthread_create(&threads[i], NULL, worker_thread, &thread_args[i]);
- }
- for (int i = 0; i < NUM_THREADS; ++i) {
- pthread_join(threads[i], NULL);
- }
- sem_destroy(&semaphore);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement