信号量的相关函数
信号量的类型 sem_t
int sem_init(sem_t *sem, int pshared, unsigned int value);
- 初始化信号量
- 参数:
- sem : 信号量变量的地址
- pshared : 0 用在线程间 ,非0 用在进程间
- value : 信号量中的值
int sem_destroy(sem_t *sem);
- 释放资源
int sem_wait(sem_t *sem);
- 对信号量加锁,调用一次对信号量的值-1,如果值为0,就阻塞
int sem_post(sem_t *sem);
- 对信号量解锁,调用一次对信号量的值+1
开发环境
Ubuntu18.04+vscode
C++标准 gnu14
使用C++的线程类实现 thread
#include<iostream>
#include<semaphore.h>
#include<unistd.h>
#include<thread>
using namespace std;
sem_t semA,semB,semC;//定义信号量
void funA(int n){
while (--n) {
sem_wait(&semA);
cout << "A:" << n << endl;
sem_post(&semB)