Boost:互斥锁

来自WHY42

示例代码

#include <iostream>
#include <vector>
#include <boost/thread.hpp>
#include <windows.h>

int sum = 0;
boost::mutex mu;
int addNum(int nCount){
	for (int i = 0; i < nCount; i++){
		boost::mutex::scoped_lock lock(mu); 
		sum++;
	}
	return sum;
}
int main(int argc, char* argv[]) {
	std::vector<boost::thread*> threads;
	for (int i = 0; i < 1000; i++) {
		boost::thread* t = new boost::thread(addNum, 1000);
		threads.push_back(t);
	}
	std::vector<boost::thread*>::iterator it;
	for (it = threads.begin(); it != threads.end(); it++) {
		boost::thread* t = *it;
		t->join();
	}
	for (int j = 0; j < 10; j++) {
		std::cout << sum << endl;
		Sleep(200);
	}
	for (it = threads.begin(); it != threads.end(); it++) {
		boost::thread* t = *it;
		delete t;
	}
	system("pause");
	return 1;
}

代码分析

如上的这一段代码,创建了1000个线程,每个线程把sum增加1000,那么程序的结果理论上应该是:

1000 * 1000 = 1000,000

如果不加锁,我们屏蔽掉boost::mutex::scoped_lock lock(mu); 这一行代码,运行一下看看:

  • 第一次

  • 第二次

  • 第三次

  • 第四次

可以看出,有几次结果都和预期的不一样,而且具有不可预料性。说明多个线程在同时写一个内存的时候,发生了错误。因此需要枷锁,加锁后,测试了大约10次,每次结果都是正确的了。说明:线程越多,越容易测试出不加锁的问题。