2010-10-18 33 views
2

我有一個線程池正在使用boost庫中的共享互斥對象。在boost中使用作用域try_shared_lock和升級鎖的示例

雖然回答我的其他問題是有幫助的, Example of how to use boost upgradeable mutexes

我已經意識到我真正需要的是不是如果共享鎖來阻止或升級無法獲得鎖。不幸的是,助推文檔缺乏使用中的示例。

有人請指點一下,或者提供一個具體的shared_lock用於這種方式的例子。

boost:shared_mutex mutex; 

void thread() 
{ 
    // try to obtain a scoped shared lock 
    // How do I do that? 
} 

void thread2() 
{ 
    // try to obtain a scoped upgrade lock 
    // and then a scoped unique lock 
} 

回答

8

答案似乎是,你可以提供升壓:try_to_lock作爲參數來幾個這樣的範圍的鎖。

例如

boost::shared_mutex mutex; 

// The reader version 
boost::shared_lock<boost::shared_mutex> lock(mutex, boost::try_to_lock); 
if (lock){ 
    // We have obtained a shared lock 
} 

// Writer version 
boost::upgrade_lock<boost::shared_mutex> write_lock(mutex, boost::try_to_lock); 
if (write_lock){ 
    boost::upgrade_to_unique_lock<boost::shared_mutex> unique_lock(write_lock); 
    // exclusive access now obtained. 
} 

編輯: 我也通過實驗,如果你沒有升級鎖upgrade_to_unique_lock將無法找到。你也可以這樣做:

boost::upgrade_to_unique_lock<boost::shared_mutex> unique_lock(write_lock); 
if (unique_lock){ 
    // we are the only thread in here... safe to do stuff to our shared resource 
} 

// If you need to downgrade then you can also call 
unique_lock.release(); 

// And if you want to release the upgrade lock as well (since only one thread can have upgraded status at a time) 
write_lock.unlock(). 

注意:你必須調用釋放,然後解鎖,否則你會得到一個鎖定異常拋出。 你當然可以讓unique_lock和write_lock超出範圍,從而釋放鎖,儘管我發現有時候你想要更早地釋放它,並且你應該在那個狀態下花費最少的時間。