#include "iostream"
#include "thread" //线程类头文件
#include "mutex" //std::once_flag和std::call_once()函数需要包含这个头文件
using namespace::std;
int flag=1;
once_flag onceFlag;//once_flag全局变量。本质是取值为0和1的锁。
//在线程中但是只调用一次的的函数
void once_func(const int bh ,const string& str)
{
cout<<"once_func() bh="<<bh<<",str="<<str<<endl;
}
//普通函数。
void func (int bh ,const string& str)
{
call_once(onceFlag,once_func,0,"各位观众,我要开始了。");
for (int ii = 0; ii <=3; ++ii) {
cout<<"第"<<ii<<"次表白:亲爱的"<<bh<<"号,"<<str<<endl;
this_thread::sleep_for(chrono::seconds(1));
}
}
int main()
{
//用普通函数创建线程。
thread t1(func,1,"我是一只傻傻鸟。");
thread t2(func,2,"我是一只小小鸟。");
t1.join(); //回收线程t1的资源。
t2.join();//回收线程t2的资源。
}
once_func() bh=0,str=各位观众,我要开始了。
第0次表白:亲爱的1第0次表白:亲爱的号,我是一只傻傻鸟。
2号,我是一只小小鸟。
第第11次表白:亲爱的1号,我是一只傻傻鸟。
次表白:亲爱的2号,我是一只小小鸟。
第2次表白:亲爱的1号,我是一只傻傻鸟。
第2次表白:亲爱的2号,我是一只小小鸟。
第3次表白:亲爱的1号,我是一只傻傻鸟。
第3次表白:亲爱的2号,我是一只小小鸟。
发表回复