🐭 const 与 mutable

C++ 类的 const 成员函数,意味着一种接口承诺,它承诺不修改对象的任何数据成员,不得调用其它非 const 成员函数,这样的成员函数无疑是线程安全的。但是 mutable 数据成员打破了这种承诺,C++ 允许 const 成员函数修改对象的 mutable 数据成员,比如 const 成员函数对锁变量的加锁和解锁就是一个典型的应用。
代码示例 :

  1. #include <iostream>
  2. #include <mutex>
  3. #include <string>
  4. #include <string_view>
  5. class Job {
  6. public:
  7. Job(std::string_view sv) : name_{sv} {}
  8. // const member function can modify
  9. // 1. mutable data member
  10. // 2. non const static data member
  11. std::string get_name() const {
  12. ++counter_;
  13. std::lock_guard g(m_);
  14. return name_;
  15. }
  16. private:
  17. mutable std::mutex m_;
  18. std::string name_;
  19. static std::atomic<size_t> counter_;
  20. };
  21. std::atomic<size_t> Job::counter_{0};
  22. int main() {
  23. Job j1{"j1"};
  24. std::cout << j1.get_name() << '\n'; // j1
  25. return 0;
  26. }

:::tips 上面的代码中,涉及到两个同步操作:

  1. std::mutex,是对象内部的同步
  2. static std::atomic,是类的所有对象之间的同步 :::

    🐂 const 与线程安全

    const 成员函数对外就意味着该接口是线程安全的,客户端代码可以不再考虑数据同步问题,那么接口设计方就应该确确实实地保证线程安全。在 C++ 中解决线程安全问题,无非是使用锁和原子变量。

  3. 原子变量比较轻便,适用于单个数据或者单块内存

  4. 锁比较通用,但开销略大

代码示例 :

  1. #include <cmath>
  2. #include <iostream>
  3. #include <mutex>
  4. class Point {
  5. public:
  6. Point(double x, double y) : x_(x), y_(y){};
  7. // the compiler generated memberwise default copy ctor can not works
  8. Point(const Point &p) {
  9. this->x_ = p.x_;
  10. this->y_ = p.y_;
  11. this->counter_ = 0;
  12. this->cache_valid_ = p.cache_valid_;
  13. this->cached_value_ = p.cached_value_;
  14. }
  15. double l2_distance() const noexcept {
  16. // record the call times
  17. // std::atomic<T> can only keep thread safe for single variable
  18. ++counter_;
  19. // record the cached value
  20. // std::mutex can keep thread safe for more than one variables
  21. std::lock_guard<std::mutex> guard(m_);
  22. if (cache_valid_) {
  23. return cached_value_;
  24. } else {
  25. std::cout << "computing the cache value ...\n"; // print out only one times
  26. cached_value_ = std::sqrt((x_ * x_) + (y_ * y_));
  27. cache_valid_ = true;
  28. return cached_value_;
  29. }
  30. }
  31. size_t call_times(void) { return counter_; }
  32. private:
  33. double x_, y_;
  34. mutable std::atomic<size_t> counter_{0};
  35. mutable std::mutex m_;
  36. mutable double cached_value_;
  37. mutable bool cache_valid_{false};
  38. };
  39. int main() {
  40. Point p{3, 4};
  41. p.l2_distance();
  42. p.l2_distance();
  43. p.l2_distance();
  44. std::cout << p.call_times() << '\n'; // 3
  45. Point p1 = p;
  46. p1.l2_distance();
  47. p1.l2_distance();
  48. std::cout << p1.call_times() << '\n'; // 2
  49. return 0;
  50. }

:::tips 锁和原子变量的引入,改变了类的属性,由于锁和原子变量都是只能移动 (move only) 的,因此持有锁和原子变量的类默认也是只能移动的,需要自己编写拷贝类操作 :::

🐯 总结

  1. 确实保证 const 成员函数是线程安全的
  2. 合理的使用锁与原子变量来保证线程安全