🐭 const 与 mutable
C++ 类的 const 成员函数,意味着一种接口承诺,它承诺不修改对象的任何数据成员,不得调用其它非 const 成员函数,这样的成员函数无疑是线程安全的。但是 mutable 数据成员打破了这种承诺,C++ 允许 const 成员函数修改对象的 mutable 数据成员,比如 const 成员函数对锁变量的加锁和解锁就是一个典型的应用。
代码示例 :
#include <iostream>#include <mutex>#include <string>#include <string_view>class Job {public:Job(std::string_view sv) : name_{sv} {}// const member function can modify// 1. mutable data member// 2. non const static data memberstd::string get_name() const {++counter_;std::lock_guard g(m_);return name_;}private:mutable std::mutex m_;std::string name_;static std::atomic<size_t> counter_;};std::atomic<size_t> Job::counter_{0};int main() {Job j1{"j1"};std::cout << j1.get_name() << '\n'; // j1return 0;}
:::tips 上面的代码中,涉及到两个同步操作:
- std::mutex,是对象内部的同步
static std::atomic
,是类的所有对象之间的同步 ::: 🐂 const 与线程安全
const 成员函数对外就意味着该接口是线程安全的,客户端代码可以不再考虑数据同步问题,那么接口设计方就应该确确实实地保证线程安全。在 C++ 中解决线程安全问题,无非是使用锁和原子变量。
原子变量比较轻便,适用于单个数据或者单块内存
- 锁比较通用,但开销略大
代码示例 :
#include <cmath>#include <iostream>#include <mutex>class Point {public:Point(double x, double y) : x_(x), y_(y){};// the compiler generated memberwise default copy ctor can not worksPoint(const Point &p) {this->x_ = p.x_;this->y_ = p.y_;this->counter_ = 0;this->cache_valid_ = p.cache_valid_;this->cached_value_ = p.cached_value_;}double l2_distance() const noexcept {// record the call times// std::atomic<T> can only keep thread safe for single variable++counter_;// record the cached value// std::mutex can keep thread safe for more than one variablesstd::lock_guard<std::mutex> guard(m_);if (cache_valid_) {return cached_value_;} else {std::cout << "computing the cache value ...\n"; // print out only one timescached_value_ = std::sqrt((x_ * x_) + (y_ * y_));cache_valid_ = true;return cached_value_;}}size_t call_times(void) { return counter_; }private:double x_, y_;mutable std::atomic<size_t> counter_{0};mutable std::mutex m_;mutable double cached_value_;mutable bool cache_valid_{false};};int main() {Point p{3, 4};p.l2_distance();p.l2_distance();p.l2_distance();std::cout << p.call_times() << '\n'; // 3Point p1 = p;p1.l2_distance();p1.l2_distance();std::cout << p1.call_times() << '\n'; // 2return 0;}
:::tips 锁和原子变量的引入,改变了类的属性,由于锁和原子变量都是只能移动 (move only) 的,因此持有锁和原子变量的类默认也是只能移动的,需要自己编写拷贝类操作 :::
🐯 总结
- 确实保证 const 成员函数是线程安全的
- 合理的使用锁与原子变量来保证线程安全
