C++核心指导原则: 并发和并行

C++ Core Guidelines 整理目录

  1. 哲学部分
  2. 接口(Interface)部分
  3. 函数部分
  4. 类和类层次结构部分
  5. 枚举部分
  6. 资源管理部分
  7. 表达式和语句部分
  8. 性能部分
  9. 并发和并行
  10. 错误处理
  11. 常量和不可变性
  12. 泛型编程
  13. 源文件
  14. 命名和布局建议
  15. 标准库
  16. 其他规则

一般规则

CP.1: Assume that your code will run as part of a multi-threaded program

CP.2: Avoid data races

CP.3: Minimize explicit sharing of writable data

CP.4: Think in terms of tasks, rather than threads

CP.8: Don’t try to use volatile for synchronization

CP.9: Whenever feasible use tools to validate your concurrent code

并发规则

CP.20: Use RAII, never plain lock()/unlock()

CP.21: Use std::lock() or std::scoped_lock to acquire multiple mutexes

CP.22: Never call unknown code while holding a lock (e.g., a callback)

CP.23: Think of a joining thread as a scoped container

CP.24: Think of a thread as a global container

CP.25: Prefer gsl::joining_thread over std::thread

CP.26: Don’t detach() a thread

CP.31: Pass small amounts of data between threads by value, rather than by reference or pointer

CP.32: To share ownership between unrelated threads use shared_ptr

CP.40: Minimize context switching

CP.41: Minimize thread creation and destruction

CP.42: Don’t wait without a condition

CP.43: Minimize time spent in a critical section

CP.44: Remember to name your lock_guards and unique_locks

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

协程规则

CP.51: Do not use capturing lambdas that are coroutines

CP.52: Do not hold locks or other synchronization primitives across suspension points

CP.53: Parameters to coroutines should not be passed by reference

消息传递规则

CP.60: Use a future to return a value from a concurrent task

CP.61: Use async() to spawn concurrent tasks

无锁编程规则

CP.100: Don’t use lock-free programming unless you absolutely have to

CP.101: Distrust your hardware/compiler combination

CP.102: Carefully study the literature

CP.110: Do not write your own double-checked locking for initialization

CP.111: Use a conventional pattern if you really need double-checked locking

其他规则

CP.200: Use volatile only to talk to non-C++ memory