2012-08-01 58 views
3

我是新来的助推线程库。我有一种情况,我在一个函数中获取scoped_lock,并需要在被调用者中等待它。boost-threads:如何将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()获取,这样我可以在其上等待。我怎么做 ? (其他一些线程会通知)。

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

任何帮助表示赞赏。谢谢 !

回答

4

传递它的参考:

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

我尝试这样做,认为这是错误的,因为我的代码被死锁。我刚刚发现那是由于别的原因。这似乎工作。谢谢 ! – 2012-08-01 17:42:00