首页 > 编程 > C++ > 正文

C++多线程编程时的数据保护

2020-05-23 14:18:38
字体:
来源:转载
供稿:网友

这篇文章主要介绍了C++多线程编程时的数据保护,作者针对C++11版本中的新特性做出了一些解说,需要的朋友可以参考下

在编写多线程程序时,多个线程同时访问某个共享资源,会导致同步的问题,这篇文章中我们将介绍 C++11 多线程编程中的数据保护。

数据丢失

让我们从一个简单的例子开始,请看如下代码:

 

 
  1. #include <iostream> 
  2. #include <string> 
  3. #include <thread> 
  4. #include <vector> 
  5.  
  6. using std::thread; 
  7. using std::vector; 
  8. using std::cout; 
  9. using std::endl; 
  10.  
  11. class Incrementer 
  12. private
  13. int counter; 
  14.  
  15. public
  16. Incrementer() : counter{0} { }; 
  17.  
  18. void operator()() 
  19. for(int i = 0; i < 100000; i++) 
  20. this->counter++; 
  21.  
  22. int getCounter() const 
  23. return this->counter; 
  24. }  
  25. }; 
  26.  
  27. int main() 
  28. // Create the threads which will each do some counting 
  29. vector<thread> threads; 
  30.  
  31. Incrementer counter; 
  32.  
  33. threads.push_back(thread(std::ref(counter))); 
  34. threads.push_back(thread(std::ref(counter))); 
  35. threads.push_back(thread(std::ref(counter))); 
  36.  
  37. for(auto &t : threads) 
  38. t.join(); 
  39.  
  40. cout << counter.getCounter() << endl; 
  41.  
  42. return 0; 

这个程序的目的就是数数,数到30万,某些傻叉程序员想要优化数数的过程,因此创建了三个线程,使用一个共享变量 counter,每个线程负责给这个变量增加10万计数。

这段代码创建了一个名为 Incrementer 的类,该类包含一个私有变量 counter,其构造器非常简单,只是将 counter 设置为 0.

紧接着是一个操作符重载,这意味着这个类的每个实例都是被当作一个简单函数来调用的。一般我们调用类的某个方法时会这样 object.fooMethod(),但现在你实际上是直接调用了对象,如object(). 因为我们是在操作符重载函数中将整个对象传递给了线程类。最后是一个 getCounter 方法,返回 counter 变量的值。

再下来是程序的入口函数 main(),我们创建了三个线程,不过只创建了一个 Incrementer 类的实例,然后将这个实例传递给三个线程,注意这里使用了 std::ref ,这相当于是传递了实例的引用对象,而不是对象的拷贝。

现在让我们来看看程序执行的结果,如果这位傻叉程序员还够聪明的话,他会使用 GCC 4.7 或者更新版本,或者是 Clang 3.1 来进行编译,编译方法:

 

 
  1. g++ -std=c++11 -lpthread -o threading_example main.cpp 

运行结果:

 

 
  1. [lucas@lucas-desktop src]$ ./threading_example 
  2. 218141 
  3. [lucas@lucas-desktop src]$ ./threading_example 
  4. 208079 
  5. [lucas@lucas-desktop src]$ ./threading_example 
  6. 100000 
  7. [lucas@lucas-desktop src]$ ./threading_example 
  8. 202426 
  9. [lucas@lucas-desktop src]$ ./threading_example 
  10. 172209 

但等等,不对啊,程序并没有数数到30万,有一次居然只数到10万,为什么会这样呢?好吧,加1操作对应实际的处理器指令其实包括:

 

 
  1. movl counter(%rip), %eax 
  2. addl $1, %eax 
  3. movl %eax, counter(%rip) 

首个指令将装载 counter 的值到 %eax 寄存器,紧接着寄存器的值增1,然后将寄存器的值移给内存中 counter 所在的地址。

我听到你在嘀咕:这不错,可为什么会导致数数错误的问题呢?嗯,还记得我们以前说过线程会共享处理器,因为只有单核。因此在某些点上,一个线程会依照指令执行完成,但在很多情况下,操作系统会对线程说:时间结束了,到后面排队再来,然后另外一个线程开始执行,当下一个线程开始执行时,它会从被暂停的那个位置开始执行。所以你猜会发生什么事,当前线程正准备执行寄存器加1操作时,系统把处理器交给另外一个线程?

我真的不知道会发生什么事,可能我们在准备加1时,另外一个线程进来了,重新将 counter 值加载到寄存器等多种情况的产生。谁也不知道到底发生了什么。

正确的做法

解决方案就是要求同一个时间内只允许一个线程访问共享变量。这个可通过 std::mutex 类来解决。当线程进入时,加锁、执行操作,然后释放锁。其他线程想要访问这个共享资源必须等待锁释放。

互斥(mutex) 是操作系统确保锁和解锁操作是不可分割的。这意味着线程在对互斥量进行锁和解锁的操作是不会被中断的。当线程对互斥量进行锁或者解锁时,该操作会在操作系统切换线程前完成。

而最好的事情是,当你试图对互斥量进行加锁操作时,其他的线程已经锁住了该互斥量,那你就必须等待直到其释放。操作系统会跟踪哪个线程正在等待哪个互斥量,被堵塞的线程会进入 "blocked onm" 状态,意味着操作系统不会给这个堵塞的线程任何处理器时间,直到互斥量解锁,因此也不会浪费 CPU 的循环。如果有多个线程处于等待状态,哪个线程最先获得资源取决于操作系统本身,一般像 Windows 和 Linux 系统使用的是 FIFO 策略,在实时操作系统中则是基于优先级的。

现在让我们对上面的代码进行改进:

 

 
  1. #include <iostream> 
  2. #include <string> 
  3. #include <thread> 
  4. #include <vector> 
  5. #include <mutex> 
  6.  
  7. using std::thread; 
  8. using std::vector; 
  9. using std::cout; 
  10. using std::endl; 
  11. using std::mutex; 
  12.  
  13. class Incrementer 
  14. private
  15. int counter; 
  16. mutex m; 
  17.  
  18. public
  19. Incrementer() : counter{0} { }; 
  20.  
  21. void operator()() 
  22. for(int i = 0; i < 100000; i++) 
  23. this->m.lock(); 
  24. this->counter++; 
  25. this->m.unlock(); 
  26.  
  27. int getCounter() const 
  28. return this->counter; 
  29. }  
  30. }; 
  31.  
  32. int main() 
  33. // Create the threads which will each do some counting 
  34. vector<thread> threads; 
  35.  
  36. Incrementer counter; 
  37.  
  38. threads.push_back(thread(std::ref(counter))); 
  39. threads.push_back(thread(std::ref(counter))); 
  40. threads.push_back(thread(std::ref(counter))); 
  41.  
  42. for(auto &t : threads) 
  43. t.join(); 
  44.  
  45. cout << counter.getCounter() << endl; 
  46.  
  47. return 0; 

注意代码上的变化:我们引入了 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操作时,是可能会发生异常的,当然在我们这个例子中发生异常的机会微乎其微,但是在一些复杂系统中是极有可能的。上面的代码并不是异常安全的,当异常发生时,程序已经结束了,可是互斥量还是处于锁的状态。

为了确保互斥量在异常发生的情况下也能被解锁,我们需要使用如下代码:

 

 
  1. for(int i = 0; i < 100000; i++) 
  2. this->m.lock(); 
  3. try 
  4. this->counter++; 
  5. this->m.unlock(); 
  6. catch(...) 
  7. this->m.unlock(); 
  8. throw

但是,这代码太多了,而只是为了对互斥量进行加锁和解锁。没关系,我知道你很懒,因此推荐个更简单的单行代码解决方法,就是使用 std::lock_guard 类。这个类在创建时就锁定了 mutex 对象,然后在结束时释放。

继续修改代码:

 

 
  1. void operator()() 
  2. for(int i = 0; i < 100000; i++) 
  3. lock_guard<mutex> lock(this->m); 
  4.  
  5. // The lock has been created now, and immediatly locks the mutex 
  6. this->counter++; 
  7.  
  8. // This is the end of the for-loop scope, and the lock will be 
  9. // destroyed, and in the destructor of the lock, it will 
  10. // unlock the mutex 

上面代码已然是异常安全了,因为当异常发生时,将会调用 lock 对象的析构函数,然后自动进行互斥量的解锁。

记住,请使用放下代码模板来编写:

 

 
  1. void long_function() 
  2. // some long code 
  3.  
  4. // Just a pair of curly braces 
  5. // Temp scope, create lock 
  6. lock_guard<mutex> lock(this->m); 
  7.  
  8. // do some stuff 
  9.  
  10. // Close the scope, so the guard will unlock the mutex 

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表