调用std::condition_variable::wait_for()崩溃,try-catch无法捕获异常求助
问题:调用
std::condition_variable::wait_for()时崩溃且无法捕获异常 我的项目调用std::condition_variable::wait_for()时总是崩溃。项目的崩溃处理程序毫无帮助,但从日志信息可以明确是wait_for()导致崩溃,可我的try-catch块无法捕获异常,完全不清楚问题所在。
工作线程需要执行任务后休眠60秒,再重复执行;为了能提前唤醒线程并退出循环,使用了std::condition_variable。以下是工作线程的代码:
static void spawned(CmdHandler *pThis) { std::unique_lock<std::mutex> lk(pThis->m_mxQuit); while (!pThis->m_bQuit) { lk.unlock(); pThis->worker.work(); lk.lock(); LOG_DEBUG << L"gonna give him wait_for() and I own the lock: " << (lk.owns_lock() ? L"true" : L"FALSE") << L"!"; try { auto ret = pThis->m_cvQuit.wait_for(lk, std::chrono::seconds(60), [&] { return pThis->m_bQuit.load(); }); LOG_DEBUG << L"and ret is (" << (ret ? L"true" : L"false") << L") and pThis->m_bQuit (" << (pThis->m_bQuit ? L"true" : L"false") << L")"; } catch (std::exception& e) { LOG_DEBUG << L"ugh: " << toWide(e.what()); } catch (...) { LOG_DEBUG << L"Unknown"; } } } std::future<void> m_threadMeta; std::condition_variable m_cvQuit; std::atomic_bool m_bQuit; std::mutex m_mxQuit;
调用spawned()的代码很简单:
m_threadMeta = std::async(std::launch::async, spawned, this);
这段代码不会锁定m_mxQuit或影响m_cvQuit,且this(即CmdHandler对象)的生命周期覆盖线程全程,析构函数未被调用。本来可以展示主线程设置m_bQuit的代码,但日志显示这段代码从未执行过,所以没必要展示。
try块前的第一条调试日志已输出,表明线程持有锁,但后续日志都未输出,显然是wait_for()导致崩溃,可我看不出调用有何问题,也无法获取日志反馈。我使用的是VS2015环境。
编辑:
根据建议,我尝试了以下代码,但问题依旧——调用wait_for()时仍崩溃:
static void spawned(CmdHandler *pThis) { bool bQuit; { std::lock_guard<std::mutex> lock(pThis->m_mxQuit); bQuit = pThis->m_bQuit; } while (!bQuit) { pThis->worker.work(); bQuit = pThis->waitForQuit(); } } bool waitForQuit() { std::unique_lock<std::mutex> lk(m_mxQuit); //wait_for() insists on unique_lock LOG_DEBUG << L"gonna give him wait_for() and I own the lock: " << (lk.owns_lock() ? L"true" : L"FALSE") << L"!"; m_cvQuit.wait_for(lk, std::chrono::seconds(60), [&] { return m_bQuit.load(); }); LOG_DEBUG << L"back and now quit is: " << (m_bQuit ? L"true" : L"FALSE") << L"!"; return m_bQuit; }
内容的提问来源于stack exchange,提问作者Opux
相关产品推荐
相关产品推荐

