問題描述
我有一個多線程應用程序,它必須經常讀取一些數據,并且偶爾會更新這些數據.現在互斥鎖可以安全地訪問該數據,但它很昂貴,因為我希望多個線程能夠同時讀取,并且僅在需要更新時將它們鎖定(更新線程可以等待其他線程完成).
I have a multithreaded app that has to read some data often, and occasionally that data is updated. Right now a mutex keeps access to that data safe, but it's expensive because I would like multiple threads to be able to read simultaneously, and only lock them out when an update is needed (the updating thread could wait for the other threads to finish).
我認為這是 boost::shared_mutex
應該做的,但我不清楚如何使用它,也沒有找到一個明確的例子.
I think this is what boost::shared_mutex
is supposed to do, but I'm not clear on how to use it, and haven't found a clear example.
有沒有人有一個簡單的例子可以讓我開始使用?
Does anyone have a simple example I could use to get started?
推薦答案
看起來你會這樣做:
boost::shared_mutex _access;
void reader()
{
// get shared access
boost::shared_lock<boost::shared_mutex> lock(_access);
// now we have shared access
}
void writer()
{
// get upgradable access
boost::upgrade_lock<boost::shared_mutex> lock(_access);
// get exclusive access
boost::upgrade_to_unique_lock<boost::shared_mutex> uniqueLock(lock);
// now we have exclusive access
}
這篇關于boost shared_mutex 的示例(多次讀取/一次寫入)?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!