我希望我的线程更优雅地关闭,所以我试图实现一个简单的信令机制.我不认为我想要一个完全事件驱动的线程,所以我有一个工人用一个方法来使用一个关键部分Monitor(相当于一个C#lock我相信)来优雅地停止它:
DrawingThread.h
class DrawingThread {
bool stopRequested;
Runtime::Monitor CSMonitor;
CPInfo *pPInfo;
//More..
}
Run Code Online (Sandbox Code Playgroud)
DrawingThread.cpp
void DrawingThread::Run() {
if (!stopRequested)
//Time consuming call#1
if (!stopRequested) {
CSMonitor.Enter();
pPInfo = new CPInfo(/**/);
//Not time consuming but pPInfo must either be null or constructed.
CSMonitor.Exit();
}
if (!stopRequested) {
pPInfo->foobar(/**/);//Time consuming and can be signalled
}
if (!stopRequested) {
//One more optional but time consuming call.
}
}
void DrawingThread::RequestStop() {
CSMonitor.Enter();
stopRequested = true;
if (pPInfo) pPInfo->RequestStop();
CSMonitor.Exit(); …Run Code Online (Sandbox Code Playgroud)