1、操作系统提供的信号量区别
2、c++20提供的信号量,只能用做同一进程间的线程同步
信号量 (semaphore) 是一种轻量的同步原件,用于制约对共享资源的并发访问。在可以使用两者时,信号量能比条件变量更有效率。
项目 | Value |
---|---|
counting_semaphore(C++20) | counting_semaphore(C++20) |
binary_semaphore(C++20) | binary_semaphore(C++20) |
1、环境配置:
a、定义于头文件
b、visual studio升级为2019
c、打开c++20支持的开关
2、使用示例
#include
#include
#include
using namespace std;
std::counting_semaphore<3> csem(0);
binary_semaphore bsem(0);
// semaphore release = condition_variable notify
// semaphore acquire = condition_variable wait
void task()
{
cout << "task:ready to recv signal \n";
csem.acquire();
cout << "task:acquire end\n";
}
int main()
{
thread t0(task);
thread t1(task);
thread t2(task);
thread t3(task);
thread t4(task);
cout << "main:ready to signal :release\n";
csem.release(3);
cout << "main: signal end\n";
t0.join();
t1.join();
t2.join();
t3.join();
t4.join();
}
如有错误或不足欢迎评论指出!创作不易,转载请注明出处。如有帮助,记得点赞关注哦(⊙o⊙)
更多内容请关注个人博客:https://blog.csdn.net/qq_43148810