首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++核心准则CP.43:尽量减少花费在临界区中的时间​

C++核心准则CP.43:尽量减少花费在临界区中的时间​

作者头像
面向对象思考
发布2020-07-16 17:30:40
6970
发布2020-07-16 17:30:40
举报

CP.43: Minimize time spent in a critical section

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<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
}
Enforcement(实施建议)

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

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

原文链接

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#cp43-minimize-time-spent-in-a-critical-section

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2020-07-12,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 面向对象思考 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • CP.43: Minimize time spent in a critical section
  • Reason(原因)
    • Enforcement(实施建议)
    领券
    问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档