示例代码
#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;
}
代码分析
如果屏蔽掉上述代码两处加锁的地方,会出现什么情况?