步骤:
初始化信号量: sem_init,设置默认信号量的值,我们下面设置为0
等待:sem_wait() 如果信号量大于0,则将信号量减一,返回成功,
如果信号量等于0,则阻塞一直等信号量大于0.
增加信号量: sem_post 加一。唤醒等待的线程。
我们下面的场景是这样的:
初始信号量为0,先启动2个线程等待这个信号量,由于为0,则被阻塞,
在另外一个线程再延迟3秒发送post,则随机唤醒前面的2个线程中的一个。
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
/**
*https://man7.org/linux/man-pages/man7/sem_overview.7.html
* https://www.geeksforgeeks.org/pthread_self-c-example/
*/
sem_t sem;
void* calls(void *ptr) {
printf("sem_wait\n");
sem_wait(&sem);
printf("continue run now\n");
return NULL;
}
void* calls3(void *ptr) {
sleep(3);
printf("post now\n");
sem_post(&sem);
sleep(3);
printf("post now\n");
sem_post(&sem);
return NULL;
}
int main() {
if (sem_init(&sem, 0, 0) == -1) {
exit(EXIT_FAILURE);
}
pthread_t thread;
pthread_t thread2;
pthread_t thread3;
pthread_create(&thread, NULL, calls, NULL);
pthread_create(&thread2, NULL, calls, NULL);
pthread_create(&thread3, NULL, calls3, NULL);
pthread_join(thread, NULL);
pthread_join(thread2, NULL);
pthread_join(thread3, NULL);
sem_destroy(&sem);
printf("main exit\n");
return EXIT_SUCCESS;
}