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

2020-07-16 17:30:40 浏览数 (2)

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(示例)

代码语言:javascript复制
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

这里,我们保持锁定的时间超出必要的限度了:我们不应该在不需要的时候获取锁,另一方面,应该在开始清理之前就释放锁。我们可以这样重写代码:

代码语言:javascript复制
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准则。作为改善,可以为临界区增加一个代码块:

代码语言:javascript复制
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

0 人点赞