#include <iostream> // std::cout
#include <thread> // std::thread
#include <mutex> // std::mutex
#include <sstream>
class testthread
{
public:
std::mutex m_mtx; // mutex for critical section
std::condition_variable condition; /*必须与unique_lock配合使用*/
int kk;
public:
void func()
{
char ss[16] = {0};
kk = 0;
std::stringstream buf;
std::this_thread::get_id()._To_text(buf);
unsigned int nId = 0;
buf >> nId;
{
std::unique_lock<std::mutex> lk(m_mtx);//unique_lock()出作用域会自动解锁
for (int i = 0; i < 9; ++i)
{
kk++;
sprintf_s(ss, "[%d]%d,%d\n", nId, kk, i);
std::cout << ss ;
if (kk == 4)
condition.wait(lk);
}
}
m_mtx.lock();
for (int i = 0; i < 12; ++i)
{
kk++;
sprintf_s(ss, "[%d]%d,%d\n", nId, kk,i);
std::cout << ss ;
}
m_mtx.unlock();
}
};
int main()
{
testthread t1;
testthread t2;
std::thread th1(&testthread::func, &t1);
std::thread th2(&testthread::func, &t2);
while (true)
{
t1.m_mtx.lock();
t1.kk = 0;
t1.m_mtx.unlock();
t1.condition.notify_all();
std::this_thread::sleep_for(std::chrono::milliseconds(2));
}
th1.join();
th2.join();
return 0;
}
代码运行结果:
[14928]1,0
[13144]1,0
[14928]2,1
[13144]2,1
[14928]3,2
[13144]3,2
[14928]4,3
[13144]4,3
[14928]1,4
[14928]2,5
[14928]3,6
[14928]4,7
[14928]1,8
[14928]2,0
[14928]3,1
[14928]4,2
[14928]5,3
[14928]6,4
[14928]7,5
[14928]8,6
[14928]9,7
[14928]10,8
[14928]11,9
[14928]12,10
[14928]13,11