如何用通过C++11提供的std::condition_variable实现主线程控制子线程的启动和停止

#include
#include              
#include               
#include                
#include   
#include
using namespace std;

bool g_bReady = false; // 是否准备好
std::mutex g_mutexReady; // g_bReady的锁
std::condition_variable g_cvReady; // g_bReady的条件变量.


bool g_bFinish = false; //是否完成任务
std::mutex g_mutexFinish;  //g_bFinish的锁
std::condition_variable g_cvFinish; // g_bFinish的条件变量


bool g_bThreadRun = false; //是否退出线程
std::mutex g_mtxThreadRun; //g_bThreadRun的锁




void do_print_id(int id)
{
while (1)
{
//等待执行任务的命令
{
std::unique_lock lck(g_mutexReady);
while (!g_bReady)
{
g_cvReady.wait(lck);
}


{
std::unique_lock lck(g_mtxThreadRun);
if (!g_bThreadRun)
{
cout << "Exit thread" << endl;
break;
}
}


//模拟任务执行
std::cout << "task " << id << " begin"< std::cout << "task " << id << " finish" << endl;

g_bReady = false;//将ready置为false,准备等待下一次的任务
}


//通知主线程完成任务
{
cout << "Notify main thread" << endl;
std::unique_lock lck(g_mutexFinish);
g_bFinish = true;
g_cvFinish.notify_all();  
}

}//while (1)
}



int main()
{
//初始化变量
g_bReady = false;
g_bFinish = false;
{
std::unique_lock lck(g_mtxThreadRun);
g_bThreadRun = true;
}



std::thread thread;
thread = std::thread(do_print_id, 1);



while (1)
{
//如果用户输入了空格键则跳出,输入了x则结束程序
while (1)
{
std::cout << "Press space to start task and press \'x\' to exit:";
string data;
getline(cin, data);
if (data == " ")
{
break;
}
else if (data == "x")
{
std::unique_lock lck(g_mtxThreadRun);
g_bThreadRun = false;
cout << "Begin Exit" << endl;
break;
}
else
{
::Sleep(10);
}
}


//通知子线程执行任务
cout << "Start the task" << endl;
{
std::unique_lock lck(g_mutexReady);
g_bReady = true; // 设置全局标志位为 true.
g_cvReady.notify_all(); // 唤醒所有线程.
}


//是否退出while循环
{
std::unique_lock lck(g_mtxThreadRun);
if (!g_bThreadRun)
{
break;
}
}


//等待任务执行完毕
{
std::unique_lock lck(g_mutexFinish);
while (!g_bFinish)
{
g_cvFinish.wait(lck);
}
g_bFinish = false; //重置bFinish状态
}

}//while(1)



thread.join();


return 0;
}

你可能感兴趣的:(如何用通过C++11提供的std::condition_variable实现主线程控制子线程的启动和停止)