日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

使用named_mutex实现锁机制

發布時間:2023/12/13 编程问答 31 豆豆
生活随笔 收集整理的這篇文章主要介紹了 使用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实现锁机制的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。