不知道是不是你要的效果// ConsoleApplication1.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
#include <thread>
#include <mutex>
#include <ostream>
#include <atomic>
#include <sstream>
using namespace std;
mutex* g_mx;
int g_cout = 0;
void t_(int param)
{
while (1)
{
int t = -1;
{
unique_lock<std::mutex> tmp(*g_mx);
t = g_cout;
}
if (t == param)
break;
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
//output
for(auto i=0;i<10;i++)
cout << "thread num:" << param << ",thread id:" << this_thread::get_id()<<endl;
{
unique_lock<std::mutex> tmp(*g_mx);
g_cout++;
}
}
int main()
{
thread* ar[3];
g_mx = new mutex;
for (auto i=0;i<3;i++)
{
ar[i] = new thread(t_,i);
ar[i]->detach();
}
getchar();
for (auto i = 0; i < 3; i++)
delete ar[i];
return 0;
}
thread num:0,thread id:1716
thread num:0,thread id:1716
thread num:0,thread id:1716
thread num:0,thread id:1716
thread num:0,thread id:1716
thread num:0,thread id:1716
thread num:0,thread id:1716
thread num:0,thread id:1716
thread num:0,thread id:1716
thread num:0,thread id:1716
thread num:1,thread id:4824
thread num:1,thread id:4824
thread num:1,thread id:4824
thread num:1,thread id:4824
thread num:1,thread id:4824
thread num:1,thread id:4824
thread num:1,thread id:4824
thread num:1,thread id:4824
thread num:1,thread id:4824
thread num:1,thread id:4824
thread num:2,thread id:14072
thread num:2,thread id:14072
thread num:2,thread id:14072
thread num:2,thread id:14072
thread num:2,thread id:14072
thread num:2,thread id:14072
thread num:2,thread id:14072
thread num:2,thread id:14072
thread num:2,thread id:14072
thread num:2,thread id:14072
|