C++核心准则CP.50:将mutex和被保护数据一起定义,如果可能使用 synchronized_value<T>

CP.50: Define a mutex together with the data it guards. Use synchronized_value where possible

CP.50:将mutex和被保护数据一起定义,如果可能使用

synchronized_value

 

Reason(原因)

It should be obvious to a reader that the data is to be guarded and how. This decreases the chance of the wrong mutex being locked, or the mutex not being locked.

数据被保护的事实以及如何被保护对于代码的读者来讲都应该是显而易见的。这可以减少锁定错误的mutex或者没有锁定正确的mutex的可能性。

Using a synchronized_value ensures that the data has a mutex, and the right mutex is locked when the data is accessed. See the WG21 proposal to add synchronized_value to a future TS or revision of the C++ standard.

使用synchronized_value可以保证数据带锁,并且数据被访问时锁定正确的mutex。参见意在向将来的技术规格或标准C++的某个版本增加synchronized_value功能的WG21。

WG21:http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2017/p0290r2.html

 

Example(示例)

struct Record {
    std::mutex m;   // take this mutex before accessing other members
    // ...
};

class MyClass {
    struct DataRecord {
       // ...
    };
    synchronized_value data; // Protect the data with a mutex
};

Enforcement(实施建议)

??? Possible?

???可能么?

 

原文链接

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#cp50-define-a-mutex-together-with-the-data-it-guards-use-synchronized_valuet-where-possible

 

新书介绍

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

 

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

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

 


 

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

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

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

 

你可能感兴趣的:(C++,C++,核心准则,mutex,保护数据,synchronize)