标签:std counting thread acquire C++ 信号量 include semaphore 多线程
https://zh.cppreference.com/w/cpp/thread/counting_semaphore
成员函数:
- release:增加内部计数器并除阻获取者
相当于V操作 - acquire: 减少内部计数器或阻塞到直至能如此
相当于p操作
#include <iostream>
#include <thread>
#include <semaphore>
using namespace std;
/*
三个线程,依次打印ABC
*/
std::counting_semaphore sema(1);
std::counting_semaphore semb(0);
std::counting_semaphore semc(0);
void thread_a()
{
for (int i = 0; i < 10; ++i)
{
sema.acquire(); // p
cout << "A";
semb.release(); // v
}
}
void thread_b()
{
for (int i = 0; i < 10; ++i)
{
semb.acquire(); // p
cout << "B";
semc.release();
}
}
void thread_c()
{
for (int i = 0; i < 10; ++i)
{
semc.acquire(); // p
cout << "C";
sema.release();
}
}
int main()
{
std::thread ta(thread_a);
std::thread tb(thread_b);
std::thread tc(thread_c);
ta.join();
tb.join();
tc.join();
return 0;
}
#include <iostream>
#include <thread>
#include <semaphore>
using namespace std;
/* 生产者,消费者模型 */
std::counting_semaphore seamp(1); // 生产者信号量
std::counting_semaphore seams(0); // 消费者信号量
int num(0);
// 生产者
void producer_thread()
{
while (num < 10)
{
seamp.acquire(); // p
num += 1;
cout << "producer: " << num << endl;
seams.release(); // v
}
}
void consumer_thread()
{
while (num < 10)
{
seams.acquire();
cout << "consumer: " << num << endl;
seamp.release();
}
}
int main()
{
std::thread tp1(producer_thread); // 生产者线程
std::thread ts1(consumer_thread); // 生产者线程
tp1.join();
ts1.join();
return 0;
}
标签:std,counting,thread,acquire,C++,信号量,include,semaphore,多线程 来源: https://blog.csdn.net/weixin_43919932/article/details/115009972
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。