为了让我们刚才的计数器结构体是线程安全的,我们添加一个 set:mutext 成员,并在每个方法中通过 lock()/unlock() 方法来进行保护:
- struct Counter { std::mutex mutex;
- int value;
- Counter() : value(0) {}
- void increment(){ mutex.lock();
- ++value; mutex.unlock();
- } };
然后我们再次测试这个程序,打印的结果就是 500 了,而且每次都一样。
异常和锁
现在让我们来看另外一种情况,想象我们的的计数器有一个减操作,并在值为0的时候抛出异常:
- struct Counter { int value;
- Counter() : value(0) {}
- void increment(){
- ++value; }
- void decrement(){
- if(value == 0){ throw "Value cannot be less than 0";
- }
- --value; }
- };










