C++20提供了counting_semaphore用于更加方便的完成对信号量的使用:
#include <iostream>
#include <thread>
#include <semaphore>
using namespace std;
counting_semaphore<1> g_sem{0};
void tFunc(int num)
{
cout<<num<<" Func begin"<<endl;
g_sem.acquire();
cout<<num<<" Func get sem and sleep begin"<<endl;
this_thread::sleep_for(1s);
cout<<num<<" Func sleep end"<<endl;
g_sem.release();
cout<<num<<" Func release sem"<<endl;
}
int main()
{
thread t1(tFunc, 1);
thread t2(tFunc, 2);
cout<<"main release sem"<<endl;
g_sem.release();
t1.join();
t2.join();
cout<<"t1 and t2 end"<<endl;
return 0;
}
运行程序输出:
main