#include <thread>
#include <iostream>
#include <mutex>
using namespace std;
int main()
{
mutex m;
thread t1([&m]()
{
this_thread::sleep_for(chrono::seconds(10));//通过sleep_for来使线程睡眠一定的时间
for (int i = 0; i < 10; i++)
{
m.lock();
cout << "In t1 ThreadID:" << this_thread::get_id() << ":" << i << endl;
m.unlock();
}
});
thread t2([&m]()
{
this_thread::sleep_for(chrono::seconds(1));//由于线程t1睡眠的时间较长,t2先执行了
for (int i = 0; i < 10;i++)
{
m.lock();
cout << "In t2 ThreadID:" << this_thread::get_id() << ":" << i << endl;
m.unlock();
}
});
t1.join();
t2.join();
cout << "Main Thread" << endl;
system("pause");
return 0;
}
#include <iostream>
#include <mutex>
using namespace std;
int main()
{
mutex m;
thread t1([&m]()
{
this_thread::sleep_for(chrono::seconds(10));//通过sleep_for来使线程睡眠一定的时间
for (int i = 0; i < 10; i++)
{
m.lock();
cout << "In t1 ThreadID:" << this_thread::get_id() << ":" << i << endl;
m.unlock();
}
});
thread t2([&m]()
{
this_thread::sleep_for(chrono::seconds(1));//由于线程t1睡眠的时间较长,t2先执行了
for (int i = 0; i < 10;i++)
{
m.lock();
cout << "In t2 ThreadID:" << this_thread::get_id() << ":" << i << endl;
m.unlock();
}
});
t1.join();
t2.join();
cout << "Main Thread" << endl;
system("pause");
return 0;
}