您好,登錄后才能下訂單哦!
這篇文章主要介紹“C++怎么實現獲得mutex鎖之后花費的時間短”,在日常操作中,相信很多人在C++怎么實現獲得mutex鎖之后花費的時間短問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對大家解答”C++怎么實現獲得mutex鎖之后花費的時間短”的疑惑有所幫助!接下來,請跟著小編一起來學習吧!
CP.43:盡量減少花費在臨界區中的時間
The less time is spent with a mutex taken, the less chance that another thread has to wait, and thread suspension and resumption are expensive.
獲得mutex鎖之后花費的時間越短,其他線程需要等待的機會就越小。線程阻塞和喚醒的代價太高了。
Example(示例)
void do_something() // bad
{
unique_lock<mutex> lck(my_lock);
do0(); // preparation: does not need lock
do1(); // transaction: needs locking
do2(); // cleanup: does not need locking
}
Here, we are holding the lock for longer than necessary: We should not have taken the lock before we needed it and should have released it again before starting the cleanup. We could rewrite this to
這里,我們保持鎖定的時間超出必要的限度了:我們不應該在不需要的時候獲取鎖,另一方面,應該在開始清理之前就釋放鎖。我們可以這樣重寫代碼:
void do_something() // bad
{
do0(); // preparation: does not need lock
my_lock.lock();
do1(); // transaction: needs locking
my_lock.unlock();
do2(); // cleanup: does not need locking
}
But that compromises safety and violates the use RAII rule. Instead, add a block for the critical section:
但是這種做法在安全方面進行了妥協,還違反了RAII準則。作為改善,可以為臨界區增加一個代碼塊:
void do_something() // OK
{
do0(); // preparation: does not need lock
{
unique_lock<mutex> lck(my_lock);
do1(); // transaction: needs locking
}
do2(); // cleanup: does not need locking
}
Impossible in general. Flag "naked" lock() and unlock().
一般情況下不可能。標記暴露的lock和unlock操作。
到此,關于“C++怎么實現獲得mutex鎖之后花費的時間短”的學習就結束了,希望能夠解決大家的疑惑。理論與實踐的搭配能更好的幫助大家學習,快去試試吧!若想繼續學習更多相關知識,請繼續關注億速云網站,小編會繼續努力為大家帶來更多實用的文章!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。