Boost:共享锁

来自WHY42
imported>Soleverlee2015年10月30日 (五) 03:01的版本 (以“=示例代码= <source lang="cpp"> #include <iostream> #include <boost/thread.hpp> #include <windows.h> int sum = 0; boost::shared_mutex mu; int write(int c){ fo...”为内容创建页面)
(差异) ←上一版本 | 最后版本 (差异) | 下一版本→ (差异)

示例代码

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

int sum = 0;
boost::shared_mutex  mu;

int write(int c){
	for (int i = 0; i < c; i++){
		boost::unique_lock<boost::shared_mutex> lock(mu);
		sum++;
		cout << "=>" << sum << endl;
	}
	return sum;
}
void read(int nCount){
	for (int i = 0; i < nCount; i++){
		boost::shared_lock<boost::shared_mutex> lock(mu);
		cout << "<=" << sum << endl;
	}
}
int main(int argc, char* argv[]) {
	boost::thread t1(write, 100);
	boost::thread t2(read, 100);
	boost::thread t3(read, 100);
	t1.join();
	t2.join();
	t3.join();
	system("pause");
	return 1;
}

代码分析

如果屏蔽掉上述代码两处加锁的地方,会出现什么情况?