boost-threads:如何将scoped_lock传递给被调用者?

时间:2012-08-01 15:32:00

标签: c++ boost boost-thread boost-mutex scoped-lock

我是boost线程库的新手。我有一种情况,我在一个函数中获得scoped_lock,需要在被调用者中等待它。

代码如下:

class HavingMutex
{
   public:
   ...
   private:
   static boost::mutex m;
   static boost::condition_variable *c;
   static void a();
   static void b();
   static void d();
}

void HavingMutex::a()
{
    boost::mutex::scoped_lock lock(m);
    ...
    b()          //Need to pass lock here. Dunno how !
}

void HavingMutex::b(lock)
{
    if (some condition)
    d(lock) // Need to pass lock here. How ?
}

void HavingMutex::d(//Need to get lock here)
{
    c->wait(lock); //Need to pass lock here (doesn't allow direct passing of mutex m)
}

基本上,在函数d()中,我需要访问我在a()中获取的作用域锁,以便我可以等待它。我怎么做 ? (其他一些线程会通知)。

或者我可以直接等待互斥锁而不是锁吗?

感谢任何帮助。谢谢!

1 个答案:

答案 0 :(得分:4)

通过引用传递:

void HavingMutex::d(boost::mutex::scoped_lock & lock)
{                                          // ^ that means "reference"
    c->wait(lock);
}