【发布时间】:2020-07-03 07:22:37
【问题描述】:
我有一个多线程应用程序,需要在中断、终止等信号时正常停止它。
这里有一个sn-p来说明逻辑的相关部分。
std::atomic_bool running = true;
std::mutex mutex;
std::condition_variable condition;
void signal_handler(int signal)
{
// in another thread `[&]() { return !running || something_to_do_conditon; } == false`
// what means continue to wait
running = false;
condition.notify_one();
// another thread goes to sleep
}
void run() {
while(true) {
std::unique_lock lock(mutex);
condition.wait_for(lock, std::chrono::hours(1), [&]() { return !running || something_to_do_conditon; });
if (!running) {
return;
}
// do smth
}
}
int main()
{
// Install a signal handler
std::signal(SIGINT, signal_handler);
std::signal(SIGTERM, signal_handler);
std::thread thread(run);
thread.join();
}
正如您在signal_handler 中看到的那样,即使running 设置为false,也可能会通知condition,仍然存在一种情况(使用内联cmets 描述),其中线程睡1小时。发生这种情况是因为 running 变量周围没有互斥锁。这允许线程在设置变量之前锁定互斥锁并检查条件。如果我添加类似
{
std::lock_guard<std::mutex> lock(mutex);
running = false;
}
在将要避免的处理程序中。
那么问题是如何使用(是否可能)互斥锁而不会出现潜在的死锁或任何其他问题。从信号中削弱睡眠线程的任何其他技巧。
【问题讨论】:
-
如何改用
promise和future,如参考:thispointer.com/c11-how-to-stop-or-terminate-a-thread -
那些只是继承了同样问题的更高级的原语,不是吗?
标签: c++ linux multithreading pthreads signals