尝试等待 boost::condition_Variable 时出现"unique_lock has no mutex: Operation not permitted"错误

"unique_lock has no mutex: Operation not permitted" error when attempting to wait on boost::condition_Variable

本文关键字:no has lock mutex Operation 错误 permitted not unique boost 等待      更新时间:2023-10-16

我正在尝试使用 boost::wait_condition 来休眠线程,直到一些新数据可用。我的函数简化为:

bool Node::waitForNewData() const
{
    boost::unique_lock<boost::mutex>(mWasNotifiedMutex);
    mWasNotified = false;
    while (true)
    {
        if (mWasNotified)
            return true;
        if (mThreadIsRequestedToStop)
            return false;
        mWasNotifiedWaitCondition.wait(mWasNotifiedMutex);
    }
}

Boost 从 wait() 函数中抛出异常,并显示以下消息:

boost unique_lock has no mutex: Operation not permitted

我正在使用这样的函数来通知等待条件:

void Node::callbackNewDataArrived()
{
    {
        boost::unique_lock<boost::mutex>(mHasNewInletDataMutex);
        mWasNotified = true;
    }
    mWasNotifiedWaitCondition.notify_all();
}

以及标头中的这些声明:

class Node
{
    // ...
    mutable bool mWasNotified;
    mutable boost::mutex mWasNotifiedMutex;
    mutable boost::condition_variable mWasNotifiedWaitCondition;
    std::atomic<bool> mThreadIsRequestedToStop;
};

我正在 Xcode 4.6.2 中构建,并在 OSX 10.8.5 上启用了 c++11 支持。我的提升库是用

./b2 toolset=clang cxxflags="-std=c++11 -stdlib=libc++ -arch i386 -arch x86_64" macosx-version=10.6 linkflags="-stdlib=libc++" --prefix=/usr/local -j 10 define=BOOST_SYSTEM_NO_DEPRECATED stage release

我链接到的提升库是

libboost_chrono.a
libboost_date_time.a
libboost_filesystem.a
libboost_system.a
libboost_thread.a

知道我在这里做错了什么吗?

boost::unique_lock<boost::mutex>(mWasNotifiedMutex);

这声明了一个名为mWasNotifiedMutex的空锁,隐藏了互斥锁本身。您打算使用互斥锁来初始化锁:

boost::unique_lock<boost::mutex> lock(mWasNotifiedMutex);

然后你需要把它而不是互斥锁交给条件变量:

mWasNotifiedWaitCondition.wait(lock);

也许你忘了链接到pthread

-lpthread