简体   繁体   English

增强互斥锁,条件,scoped_lock,我在这里使用错吗?

[英]boost mutex, condition, scoped_lock , am I using them wrong here?

class MyClass
{
public:
    void PushMessage(MyMessage m) // Thread 1 calls this
    {
        boost::mutex::scoped_lock lock(mMutex);
        mQueue.push_back(m);
        mCondition.notify_one();
    }

    MyMessage PopMessage()
    {
        boost::mutex::scoped_lock lock(mMutex);
        while(mQueue.empty())
            mCondition.wait(lock);

        MyMessage message = mQueue.front();
        mQueue.pop_front();
        return message;
    }

    void foo() // thread 2 is running this loop, and supposed to get messages
    {
        for(;;)
        {
            MyMessage message = PopMessage();

            do_something(message);
        }
    }
private:
    std::deque<MyMessage> mQueue;

    boost::mutex mMutex;
    boost::condition mCondition;
};

When I run the code, PushMessage is called, and foo() is waiting on PopMessage() , but PopMessage never returns. 当我运行代码时,将调用PushMessage ,并且foo()会在PopMessage()上等待,但PopMessage永远不会返回。

What does do_something here is not irrelevant I think. 我认为这里的do_something并不是无关紧要的。

What am I doing wrong here? 我在这里做错了什么? Strangely, the above code worked fine under mac, but I'm having trouble on linux. 奇怪的是,以上代码在mac上运行良好,但是在linux上却遇到了麻烦。
boost version is 1.44.0 Boost版本为1.44.0

Thank you 谢谢

Rather than letting the scope of the lock object expire before it unlocks, you could try to manually unlock the mutex in PushMessage() before you unblock the waiting thread, ie, 您可以尝试在解除阻止等待线程之前尝试在PushMessage()手动解锁互斥锁,而不是让锁定对象的作用域在解锁之前就失效。

void PushMessage(MyMessage m) // Thread 1 calls this
{
    boost::mutex::scoped_lock lock(mMutex);
    mQueue.push_back(m);

    lock.unlock(); // <== manually unlock

    mCondition.notify_one();
}

That way when thread 2 unblocks, there will be no "cross-over" time where thread 1 contains the lock, and thread 2 is trying to obtain a lock on your mutex. 这样,当线程2解除阻塞时,在线程1包含锁且线程2试图在互斥锁上获得锁的情况下,将没有“跨接”时间。 I don't see why that would create problems, but again, at least you won't have thread 2 trying to call lock.lock() while thread 1 still contains the lock. 我不知道为什么会造成问题,但是同样,至少线程2仍包含锁时,至少您不会让线程2尝试调用lock.lock()

I think you need 2 mutex objects, one is for synchronizing method call in different threads, one is for condition wait. 我认为您需要2个互斥对象,一个用于在不同线程中同步方法调用,一个用于条件等待。 You mixed them. 你把它们混合了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM