成都创新互联网站制作重庆分公司

C++怎么实现获得mutex锁之后花费的时间短

这篇文章主要介绍“C++怎么实现获得mutex锁之后花费的时间短”,在日常操作中,相信很多人在C++怎么实现获得mutex锁之后花费的时间短问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”C++怎么实现获得mutex锁之后花费的时间短”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!

我们提供的服务有:成都做网站、成都网站设计、成都外贸网站建设、微信公众号开发、网站优化、网站认证、舟山ssl等。为上千家企事业单位解决了网站和推广的问题。提供周到的售前咨询和贴心的售后服务,是有科学管理、有技术的舟山网站制作公司

CP.43:尽量减少花费在临界区中的时间

Reason(原因)

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 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 lck(my_lock);
       do1();  // transaction: needs locking
   }
   do2();  // cleanup: does not need locking
}
Enforcement(实施建议)

Impossible in general. Flag "naked" lock() and unlock().

一般情况下不可能。标记暴露的lock和unlock操作。

到此,关于“C++怎么实现获得mutex锁之后花费的时间短”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注创新互联网站,小编会继续努力为大家带来更多实用的文章!


网站名称:C++怎么实现获得mutex锁之后花费的时间短
链接分享:http://cxhlcq.com/article/jspphs.html

其他资讯

在线咨询

微信咨询

电话咨询

028-86922220(工作日)

18980820575(7×24)

提交需求

返回顶部