c++11 实现两个线程交替同步

2018-01-27 10:27:06来源:网络收集作者:程序诗人人点击

分享
#include
#include
#include
#include
std::mutex data_mutex;
std::condition_variable data_var;
bool label = false;
void printodd()
{
std::unique_lock ulock(data_mutex);
for (int odd = 1; odd <= 100; odd += 2)
{
data_var.wait(ulock, [] {return label; });
std::cout << std::this_thread::get_id() << ": " << odd << " labelA= "<label = false;
data_var.notify_one();
}
}
void printeven()
{
std::unique_lock ulock(data_mutex);
for (int even = 0; even < 100; even += 2)
{
std::cout << std::this_thread::get_id() << ": " << even << " labelB= " << label<< std::endl;
data_var.notify_one();
label = true;
data_var.wait(ulock, [] {return !label; });
}
}
int main()
{
std::thread t1(printeven);
std::thread t2(printodd);
t1.join();
t2.join();
std::cout << "end!" << std::endl;
getchar();
return 0;
}

最新文章

123

最新摄影

微信扫一扫

第七城市微信公众平台