boost读写锁测试代码
两个线程可以同时读。但是有写的时候,是全部锁定。
#include <boost/thread.hpp> #include <thread> int _tmain(int argc, _TCHAR* argv[]) { std::vector<int> items; boost::shared_mutex mutex; std::thread r1([&]() mutable { while (true) { std::cout << "1:我要读10秒" << std::endl; boost::shared_lock<boost::shared_mutex> lk(mutex); std::cout << "1:等着吧" << std::endl; std::this_thread::sleep_for(std::chrono::seconds(10)); std::cout << "1:我读完了" << std::endl; } }); std::thread r2([&]() mutable { while(1){ { std::cout << "2:我要瞬间读" << std::endl; boost::shared_lock<boost::shared_mutex> lk(mutex); std::cout << "2:读到了" << std::endl; } std::this_thread::sleep_for(std::chrono::seconds(1)); } }); while (true) { int value = 0; std::cin >> value; std::cout << "3:我想要写:" << std::endl; { boost::unique_lock<boost::shared_mutex> lk(mutex); items.push_back(value); std::cout << "3:写完了"; }; } system("pause"); return 0; }
本博客注有“转”字样的为转载文章,其余为本人原创文章,转载请务必注明出处或保存此段。c++/lua/windows逆向交流群:69148232