2012-07-07 64 views
4

我有一個需要評論的基本示例(C++)。Boost爲同一個線程獲得多個鎖

比方說,我有一個函數PublicFunc(),另一個名爲PrivateFunc()。我想仔細地同步它們。但是PrivateFunc有時也可以調用PublicFunc,以及我們從同一個線程調用它的方式。這會導致塊,我想解決它。

mutable boost::mutex m; 

void PublicFunc() { 
m.lock(); 
//Here it blocks, but why? 
//What I need is to get the lock if this func was called from PrivateFunc(), so exactly from the same thread. 
//But! It should definitely block on calling PublicFunc from outside while we are for example in the 'OtherPrivateFunc'. 

//Do some stuff 

//this is not necessary 
m.unlock(); 
} 

void PrivateFunc() { 
m.lock(); 

PublicFunc(); 

OtherPrivateFunc(); 

m.unlock(); 
} 

哪個互斥鎖或鎖是從boost庫中正確的? 謝謝!

回答

4

A mutex只能鎖定一次;即使鎖定互斥鎖的嘗試由鎖定互斥鎖的線程創建,任何鎖定互鎖鎖定的調用都將被阻止。

如果您希望能夠在同一個線程上多次鎖定互斥鎖,請使用recursive_mutex

或者,考慮重組您的代碼,以便您擁有一組假設互斥鎖被鎖定的(私有)成員函數,並將所有其他函數委派給這些成員函數。這可以使代碼更清晰並且可以更容易地驗證同步是否正確。