我已将信号量初始化为0。我通过创建三个线程,然后调用sema_func()来启动程序,其中sema_wait()将其放入等待列表中。现在,我创建了第4个线程,该线程通过调用sema_wake()函数唤醒其中一个线程。但是,当所有线程唤醒时,我是否应该将最终值从0而不是1改为0?请指导我
我的代码:
#include <pthread.h>
#include <stdio.h>
#include <semaphore.h>
sem_t mySema;
void *sema_func(void *param) {
printf("SLEEPING THREAD %lu \n", pthread_self());
sem_wait(&mySema);
printf("WOKE THREAD %lu \n", pthread_self());
sleep(1);
sem_post(&mySema);
}
void *wake_func(void *param) {
int sema_value = 0;
sem_getvalue(&mySema, &sema_value);
printf("SEMA VALUE: %d\n", sema_value);
sem_post(&mySema);
sleep(5);
sem_getvalue(&mySema, &sema_value);
printf("SEMA FINAL VALUE: %d\n", sema_value);
}
int main(int argc, char *argv[]) {
sem_init(&mySema, 0, 0);
pthread_t t1; pthread_t t2; pthread_t t3; pthread_t t4;
pthread_create(&t1, NULL, sema_func, NULL);
pthread_create(&t2, NULL, sema_func, NULL);
pthread_create(&t3, NULL, sema_func, NULL);
sleep(4);
pthread_create(&t4, NULL, wake_func, NULL);
sleep(10);
}
输出:-