在编写多线程程序时,多个线程同时访问某个共享资源,会导致同步的问题,这篇文章中我们将介绍 C++11 多线程编程中的数据保护。
数据丢失
让我们从一个简单的例子开始,请看如下代码:
01 |
#include <iostream> |
02 |
#include <string> |
03 |
#include <thread> |
04 |
#include <vector> |
05 |
06 |
using std::thread;
|
07 |
using std::vector;
|
08 |
using std::cout;
|
09 |
using std::endl;
|
10 |
11 |
class Incrementer
|
12 |
{ |
13 |
private:
|
14 |
int counter;
|
15 |
16 |
public:
|
17 |
Incrementer() : counter{0} { };
|
18 |
19 |
void operator()()
|
20 |
{
|
21 |
for(int i = 0; i < 100000; i++)
|
22 |
{
|
23 |
this->counter++;
|
24 |
}
|
25 |
}
|
26 |
27 |
int getCounter() const
|
28 |
{
|
29 |
return this->counter;
|
30 |
}
|
31 |
}; |
32 |
33 |
int main()
|
34 |
{ |
35 |
// Create the threads which will each do some counting
|
36 |
vector<thread> threads;
|
37 |
38 |
Incrementer counter;
|
39 |
40 |
threads.push_back(thread(std::ref(counter)));
|
41 |
threads.push_back(thread(std::ref(counter)));
|
42 |
threads.push_back(thread(std::ref(counter)));
|
43 |
44 |
for(auto &t : threads)
|
45 |
{
|
46 |
t.join();
|
47 |
}
|
48 |
49 |
cout << counter.getCounter() << endl;
|
50 |
51 |
return 0;
|
52 |
} |