信号量的相关函数
信号量的类型 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);
}
}
void funB(int n){
while (--n) {
sem_wait(&semB);
cout << "B:" << n << endl;
sem_post(&semC);
}
}
void funC(int n){
while (--n) {
sem_wait(&semC);
cout << "C:" << n << endl;
sem_post(&semA);
}
}
int main(){
//初始化信号量
sem_init(&semA,0,1);
sem_init(&semB,0,0);
sem_init(&semC,0,0);
//创建3个线程
thread tidA,tidB,tidC;
int num=10;//执行次数
tidA=thread(funA, num);
tidB=thread(funB, num);
tidC=thread(funC, num);
//等待线程结束 回收资源
tidA.join();
tidB.join();
tidC.join();
return 0;
}
编译执行 要加上-lpthread的库 因为thread的内部也是用pthread实现的

使用C语言中的pthread_creat创建线程
#include<iostream>
#include<semaphore.h>
#include<unistd.h>
#include<pthread.h>
using namespace std;
sem_t semA,semB,semC;//定义信号量
void* funA(void* arg){
int n=*(int *)arg;
while (--n) {
sem_wait(&semA);
cout << "A:" << n << endl;
sem_post(&semB);
}
}
void* funB(void* arg){
int n=*(int *)arg;
while (--n) {
sem_wait(&semB);
cout << "B:" << n << endl;
sem_post(&semC);
}
}
void* funC(void* arg){
int n=*(int *)arg;
while (--n) {
sem_wait(&semC);
cout << "C:" << n << endl;
sem_post(&semA);
}
}
int main(){
//初始化信号量
sem_init(&semA,0,1);
sem_init(&semB,0,0);
sem_init(&semC,0,0);
//创建3个线程
pthread_t tidA,tidB,tidC;
int num=10;//执行10次
pthread_create(&tidA, NULL, funA, (void *)&num);
pthread_create(&tidB, NULL, funB, (void *)&num);
pthread_create(&tidC, NULL, funC, (void *)&num);
//等待线程结束 回收资源
pthread_join(tidA,NULL);
pthread_join(tidB,NULL);
pthread_join(tidC,NULL);
//销毁信号量
sem_destroy(&semA);
sem_destroy(&semB);
sem_destroy(&semC);
pthread_exit(NULL);
return 0;
}
编译操作同上,执行的效果相同,
1252



被折叠的 条评论
为什么被折叠?



