使用named_mutex实现锁机制
                                                            生活随笔
收集整理的這篇文章主要介紹了
                                使用named_mutex实现锁机制
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.                        
                                介紹
- named_mutex是一個進程鎖,考慮到進程和線程之間的區別
- 區別:一個工作單元要想被稱作進程,它必須要有操作系統指派給他的地址空間,必須擁有進程ID,必須擁有狀態和進程表中的表項。進程和線程之間最大的區別是進程有著自己的地址空間,而線程共享創建它們的進程的地址空間。
- 本例子是使用多線程的方式來測進程鎖的線程安全
- 等一切結束的時候,好好總結一下,完善這個大坑
代碼
#include <boost/thread/thread.hpp> #include <boost/interprocess/sync/scoped_lock.hpp> #include <boost/interprocess/sync/named_mutex.hpp> #include <boost/ref.hpp>#include <string> #include <mutex>//boost::shared_mutex global_mutex; int global_num = 10;//全局變量,寫者改變全局變量,讀者讀全局變量 namespace bip = boost::interprocess; bip::named_mutex global_mutex(bip::open_or_create,"mtx");//讀線程 void read_thread(std::string &name){boost::lock_guard<bip::named_mutex> lock(global_mutex);//讀鎖定 // bip::named_mutex global_mutex(bip::open_or_create,"mtx"); // global_mutex.lock();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()); // global_mutex.unlock(); }//寫線程 void write_thread(std::string &name){std::lock_guard<bip::named_mutex> lock(global_mutex);//寫鎖定 // bip::named_mutex global_mutex(bip::open_or_create,"mtx"); // global_mutex.lock();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()); // global_mutex.unlock(); }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";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.join_all();return 0; }參考鏈接
- 使用boost.threads的condition構造的讀寫鎖
總結
以上是生活随笔為你收集整理的使用named_mutex实现锁机制的全部內容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: 无需审核通过贷款,银行贷款被拒绝如何处理
- 下一篇: 300开头的股票涨跌幅是多少
