这篇文章主要介绍“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进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。