問(wèn)題描述
我有一個(gè)多線程應(yīng)用程序,它必須經(jīng)常讀取一些數(shù)據(jù),并且偶爾會(huì)更新這些數(shù)據(jù).現(xiàn)在互斥鎖可以安全地訪問(wèn)該數(shù)據(jù),但它很昂貴,因?yàn)槲蚁M鄠€(gè)線程能夠同時(shí)讀取,并且僅在需要更新時(shí)將它們鎖定(更新線程可以等待其他線程完成).
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).
我認(rèn)為這是 boost::shared_mutex
應(yīng)該做的,但我不清楚如何使用它,也沒(méi)有找到一個(gè)明確的例子.
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.
有沒(méi)有人有一個(gè)簡(jiǎn)單的例子可以讓我開(kāi)始使用?
Does anyone have a simple example I could use to get started?
推薦答案
看起來(lái)你會(huì)這樣做:
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
}
這篇關(guān)于boost shared_mutex 的示例(多次讀取/一次寫(xiě)入)?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!