您最好通过一些同步对象(事件、锁、互斥锁、信号量、临界区等)等来同步线程,以便主线程可以等待工作线程。
这里有一个竞争条件:如果在if
评估条件之后和执行 DB 操作之前立即引发关闭标志怎么办?
这是一个使用互斥锁作为众所周知的同步原语的插图,但还有更好的方法。
主线程:
int main() {
... wait for signal to exit the app
// the DB operations are running on another thread
...
// assume that we start shutdown here
// also assume that there is some global mutex g_mutex
// following line blocks if mutex is locked in worker thread:
std::lock_guard<std::mutex> lock(g_mutex);
Cleanup(); // should also ensure that worker is stopped
}
工作线程:
void MyWorkerThread::RunMethod()
{
{
std::lock_guard<std::mutex> lock(g_mutex);
DoSomethingOnDB();
}
// some other, non locked execution which doesn't prevent
// main thread from exiting
...
{
std::lock_guard<std::mutex> lock(g_mutex);
DoSomethingMoreOnDB();
}
}
显然你不想重复所有的锁定,你应该把它包装起来:
void MyWorkerThread::RunMethod()
{
Execute(DoSomethingOnDB);
...
Execute(DoSomethingMoreOnDB);
}
void MyWorkerThread::Execute(DatabaseFn fn)
{
std::lock_guard<std::mutex> lock(g_mutex);
fn();
}