使用named_mutex和named_condition配合实现读写锁
生活随笔
收集整理的這篇文章主要介紹了
使用named_mutex和named_condition配合实现读写锁
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
代碼
- 代碼的名稱是read_write_mutex.h
- 初步優化
- 如果涉及到進程掛掉了,造成進程堵塞,如何解決?還未涉及
測試程序
#include <boost/thread/thread.hpp> #include <boost/interprocess/sync/scoped_lock.hpp> #include <boost/ref.hpp>#include "read_write_mutex.h"#include <string>chy::shared_mutex global_mutex; int global_num = 10;//全局變量,寫者改變全局變量,讀者讀全局變量 namespace bip = boost::interprocess;//讀線程 void read_thread(std::string &name){boost::shared_lock<chy::shared_mutex> lock{global_mutex};printf("線程%s搶占了資源,global_num = %d\n",name.c_str(),global_num);boost::this_thread::sleep(boost::posix_time::seconds(1));printf("線程%s釋放了資源...\n",name.c_str()); }//寫線程 void write_thread(std::string &name){boost::lock_guard<chy::shared_mutex> lock{global_mutex};global_num++;//寫線程改變數據的數值printf("線程%s搶占了資源,global_num = %d\n",name.c_str(),global_num);boost::this_thread::sleep(boost::posix_time::seconds(1));printf("線程%s釋放了資源...\n",name.c_str()); }int main(){std::string read_thread_r1 = "read_thread_r1";std::string read_thread_r2 = "read_thread_r2";std::string read_thread_r3 = "read_thread_r3";std::string read_thread_r4 = "read_thread_r4";std::string read_thread_r5 = "read_thread_r5";std::string write_thread_w1 = "write_thread_w1";std::string write_thread_w2 = "write_thread_w2"; // std::string write_thread_w3 = "write_thread_w3"; // std::string write_thread_w4 = "write_thread_w4";boost::thread_group tg;tg.create_thread(boost::bind(read_thread,boost::ref(read_thread_r1)));tg.create_thread(boost::bind(read_thread,boost::ref(read_thread_r2)));tg.create_thread(boost::bind(read_thread,boost::ref(read_thread_r3)));tg.create_thread(boost::bind(read_thread,boost::ref(read_thread_r4)));tg.create_thread(boost::bind(read_thread,boost::ref(read_thread_r5)));tg.create_thread(boost::bind(write_thread,boost::ref(write_thread_w1)));tg.create_thread(boost::bind(write_thread,boost::ref(write_thread_w2))); // tg.create_thread(boost::bind(write_thread,boost::ref(write_thread_w3))); // tg.create_thread(boost::bind(write_thread,boost::ref(write_thread_w4)));tg.join_all();return 0; }?
總結
以上是生活随笔為你收集整理的使用named_mutex和named_condition配合实现读写锁的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 代码重构 防火墙 相关知识
- 下一篇: 王道考研 计算机网络16网络层功能 数据