曾经在《Modern C++ 条件变量》提到过可以用GDB来模拟线程调度来解释为什么打印“this is fun2,count=6” 而不是“this is fun2,count=5”。
#include <iostream>
#include <thread>
#include <condition_variable>
#include <mutex>
#include <unistd.h>
using namespace std;
//全局条件变量
condition_variable cond;
mutex _mutex;
int count = 0;
void fun1(){
while(1)
{
count++;
unique_lock<mutex>lock(_mutex);
if(count%5 == 0)
{
cond.notify_one();
}
else
{
cout<<"this is fun1,count="<<count<<endl;
}
lock.unlock();
}
}
void fun2()
{
while(1)
{
unique_lock<mutex>lock(_mutex);
cond.wait(lock);
sleep(2);
cout<<"this is fun2,count="<<count<<endl;
lock.unlock();
}
}
int main()
{