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:///isocpp/CppCoreGuidelines/blob/master/#cp43-minimize-time-spent-in-a-critical-section​

 

新书介绍

以下是本人3月份出版的新书,拜托多多关注!

 

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

本书利用Python 的标准GUI 工具包tkinter,通过可执行的示例对23 个设计模式逐个进行说明。这样一方面可以使读者了解真实的软件开发工作中每个设计模式的运用场景和想要解决的问题;另一方面通过对这些问题的解决过程进行说明,让读者明白在编写代码时如何判断使用设计模式的利弊,并合理运用设计模式。

对设计模式感兴趣而且希望随学随用的读者通过本书可以快速跨越从理解到运用的门槛;希望学习Python GUI 编程的读者可以将本书中的示例作为设计和开发的参考;使用Python 语言进行图像分析、数据处理工作的读者可以直接以本书中的示例为基础,迅速构建自己的系统架构。

 


 

觉得本文有帮助?请分享给更多人。

关注微信公众号【面向对象思考】轻松学习每一天!

面向对象开发,面向对象思考!

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