正确的做法
解决方案就是要求同一个时间内只允许一个线程访问共享变量。这个可通过 std::mutex 类来解决。当线程进入时,加锁、执行操作,然后释放锁。其他线程想要访问这个共享资源必须等待锁释放。
互斥(mutex) 是操作系统确保锁和解锁操作是不可分割的。这意味着线程在对互斥量进行锁和解锁的操作是不会被中断的。当线程对互斥量进行锁或者解锁时,该操作会在操作系统切换线程前完成。
而最好的事情是,当你试图对互斥量进行加锁操作时,其他的线程已经锁住了该互斥量,那你就必须等待直到其释放。操作系统会跟踪哪个线程正在等待哪个互斥量,被堵塞的线程会进入 "blocked on m" 状态,意味着操作系统不会给这个堵塞的线程任何处理器时间,直到互斥量解锁,因此也不会浪费 CPU 的循环。如果有多个线程处于等待状态,哪个线程最先获得资源取决于操作系统本身,一般像 Windows 和 Linux 系统使用的是 FIFO 策略,在实时操作系统中则是基于优先级的。
现在让我们对上面的代码进行改进:
01 |
#include <iostream> |
02 |
#include <string> |
03 |
#include <thread> |
04 |
#include <vector> |
05 |
#include <mutex> |
06 |
|
07 |
using std::thread; |
08 |
using std::vector; |
09 |
using std::cout; |
10 |
using std::endl; |
11 |
using std::mutex; |
12 |
|
13 |
class Incrementer |
14 |
{ |
15 |
private: |
16 |
int counter; |
17 |
mutex m; |
18 |
|
19 |
public: |
20 |
Incrementer() : counter{0} { }; |
21 |
|
22 |
void operator()() |
23 |
{ |
24 |
for(int i = 0; i < 100000; i++) |
25 |
{ |
26 |
this->m.lock(); |
27 |
this->counter++; |
28 |
this->m.unlock(); |
29 |
} |
30 |
} |
31 |
|
32 |
int getCounter() const |
33 |
{ |
34 |
return this->counter; |
35 |
} |
36 |
}; |
37 |
|
38 |
int main() |
39 |
{ |
40 |
// Create the threads which will each do some counting |
41 |
vector<thread> threads; |
42 |
|
43 |
Incrementer counter; |
44 |
|
45 |
threads.push_back(thread(std::ref(counter))); |
46 |
threads.push_back(thread(std::ref(counter))); |
47 |
threads.push_back(thread(std::ref(counter))); |
48 |
|
49 |
for(auto &t : threads) |
50 |
{ |
51 |
t.join(); |
52 |
} |
53 |
|
54 |
cout << counter.getCounter() << endl; |
55 |
|
56 |
return 0; |
57 |
} |
注意代码上的变化:我们引入了 mutex 头文件,增加了一个 m 的成员,类型是 mutex,在 operator()() 中我们锁住互斥量 m 然后对 counter 进行加1操作,然后释放互斥量。
再次执行上述程序,结果如下:
1 |
[lucas@lucas-desktop src]$ ./threading_example |
2 |
300000 |
3 |
[lucas@lucas-desktop src]$ ./threading_example |
4 |
300000 |
这下数对了。不过在计算机科学中,没有免费的午餐,使用互斥量会降低程序的性能,但这总比一个错误的程序要强吧。
防范异常
当对变量进行加1操作时,是可能会发生异常的,当然在我们这个例子中发生异常的机会微乎其微,但是在一些复杂系统中是极有可能的。上面的代码并不是异常安全的,当异常发生时,程序已经结束了,可是互斥量还是处于锁的状态。
为了确保互斥量在异常发生的情况下也能被解锁,我们需要使用如下代码:
01 |
for(int i = 0; i < 100000; i++) |
02 |
{ |
03 |
this->m.lock(); |
04 |
try |
05 |
{ |
06 |
this->counter++; |
07 |
this->m.unlock(); |
08 |
} |
09 |
catch(...) |
10 |
{ |
11 |
this->m.unlock(); |
12 |
throw; |
13 |
} |
14 |
} |
但是,这代码太多了,而只是为了对互斥量进行加锁和解锁。没关系,我知道你很懒,因此推荐个更简单的单行代码解决方法,就是使用 std::lock_guard 类。这个类在创建时就锁定了 mutex 对象,然后在结束时释放。
继续修改代码:
01 |
void operator()() |
02 |
{ |
03 |
for(int i = 0; i < 100000; i++) |
04 |
{ |
05 |
lock_guard<mutex> lock(this->m); |
06 |
|
07 |
// The lock has been created now, and immediatly locks the mutex |
08 |
this->counter++; |
09 |
|
10 |
// This is the end of the for-loop scope, and the lock will be |
11 |
// destroyed, and in the destructor of the lock, it will |
12 |
// unlock the mutex |
13 |
} |
14 |
} |
上面代码已然是异常安全了,因为当异常发生时,将会调用 lock 对象的析构函数,然后自动进行互斥量的解锁。
记住,请使用放下代码模板来编写:
01 |
void long_function() |
02 |
{ |
03 |
// some long code |
04 |
|
05 |
// Just a pair of curly braces |
06 |
{ |
07 |
// Temp scope, create lock |
08 |
lock_guard<mutex> lock(this->m); |
09 |
|
10 |
// do some stuff |
11 |
|
12 |
// Close the scope, so the guard will unlock the mutex |
13 |
} |
14 |
} |
