使用named_mutex和named_condition配合實現讀寫鎖

代碼

  • 代碼的名稱是read_write_mutex.h
  • 初步優化
  • 如果涉及到進程掛掉了,造成進程堵塞,如何解決?還未涉及
#include <boost/interprocess/sync/named_condition.hpp>
#include <boost/interprocess/sync/named_mutex.hpp>namespace bip = boost::interprocess;
namespace chy{class shared_mutex{private:class state_data{public:state_data() :shared_count(0),exclusive(false),exclusive_waiting_blocked(false){}void assert_free() const{BOOST_ASSERT( ! exclusive );BOOST_ASSERT( shared_count==0);}void assert_locked() const{BOOST_ASSERT( exclusive);BOOST_ASSERT( shared_count==0);}void assert_lock_shared() const{BOOST_ASSERT( !exclusive);BOOST_ASSERT( shared_count>0 );}bool can_lock() const{return ! (shared_count || exclusive);}void exclusive_blocked (bool blocked){exclusive_waiting_blocked = blocked;}void lock(){exclusive = true;};void unlock(){exclusive = false;exclusive_waiting_blocked = false;}bool can_lock_shared() const{return !(exclusive || exclusive_waiting_blocked);}bool more_shared() const{return shared_count > 0;}uint8_t get_shared_count() const{return shared_count;}uint8_t lock_shared(){return ++shared_count;}uint8_t unlock_shared(){return --shared_count;}//TODO shared_count 的類型最好不要使用unsignedunsigned shared_count;//讀者數量bool exclusive;//表示已經加了寫鎖,進入互斥狀態bool exclusive_waiting_blocked;//表示即將加寫鎖,當其為true的時候,不可以加讀鎖,此時寫鎖競爭};state_data state;//TODO 將文件的名字和named_mutex和named_condition綁定在一起bip::named_mutex state_change{bip::open_or_create,"mutex"};bip::named_condition shared_cond{bip::open_or_create,"read"};bip::named_condition exclusive_cond{bip::open_or_create,"write"};void release_waiters(){exclusive_cond.notify_one();shared_cond.notify_all();}public:shared_mutex()=default;~shared_mutex()=default;void lock_shared(){boost::unique_lock<bip::named_mutex>lk(state_change);while (!state.can_lock_shared()){shared_cond.wait(lk);}state.lock_shared();}bool try_lock_shared(){boost::unique_lock<bip::named_mutex>lk(state_change);if (!state.can_lock_shared()){return false;}state.lock_shared();return true;}void unlock_shared(){boost::unique_lock<bip::named_mutex>lk(state_change);state.assert_lock_shared();state.unlock_shared();if (! state.more_shared()){state.exclusive_waiting_blocked = false;release_waiters();}}void lock(){boost::unique_lock<bip::named_mutex>lk(state_change);while (state.shared_count || state.exclusive){state.exclusive_waiting_blocked=true;exclusive_cond.wait(lk);}state.exclusive=true;}bool try_lock(){boost::unique_lock<bip::named_mutex>lk(state_change);if (state.shared_count || state.exclusive){return false;} else{state.exclusive=true;return true;}}void unlock(){boost::unique_lock<bip::named_mutex>lk(state_change);state.assert_locked();state.exclusive= false;state.exclusive_waiting_blocked= false;state.assert_free();release_waiters();}};
}//namespace chy

測試程序

#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;
}

?

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/446813.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/446813.shtml
英文地址,請注明出處:http://en.pswp.cn/news/446813.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

C++的輸入與輸出

輸入與輸出 輸入:從外部輸入設備(鍵盤)向計算機輸入數據 輸出:從計算機向外部輸出設備(顯示屏)輸出數據 C使用流對象實現 使用流對象cin與cout,將標準輸入輸出流庫的頭文件iostream包含到源文件 #include<iostream>//標準輸入輸出庫 using namespace std;//使用標準命…

Android 動態計算ListView的高度

目錄一、簡介二、效果圖三、代碼實現一、簡介 在Android開發的過程中有的時候我們需要手動計算ListView的高度&#xff0c;比如說&#xff0c;ScrollView中嵌套ListView的時候&#xff0c;我們就需要手動精確計算ListView的高度了。 如果ListView的Item高度是固定的話還好計算…

DjangoRestFramework(drf實現五個接口)

安裝&#xff1a;pip install djangorestframework 在使用drf之前&#xff0c;先 使用原生Django實現5個接口 models.py from django.db import modelsclass Book(models.Model):namemodels.CharField(max_length53)pricemodels.IntegerField() views.py from app01 impor…

linux使用共享內存進行進程通信

一、什么是共享內存 共享內存就是允許兩個不相關的進程訪問同一個邏輯內存。共享內存是在兩個正在運行的進程之間共享和傳遞數據的一種非常有效的方式。不同進程之間共享的內存通常為同一段物理內存。使用共享內存進行通信的進程都需要同一段共享內存連接到它們自己的地址空間…

安卓TextView文本框與自定義邊框

常用屬性 自定義邊框 基本使用 <?xml version"1.0" encoding"utf-8"?> <shape xmlns:android"http://schemas.android.com/apk/res/android"android:shape"rectangle矩形/ring圓環/oval橢圓/line直線"當為圓環時android:s…

Android RecyclerView實現九宮格效果

RecyclerView更加優化的復用機制和方便實現UI效果&#xff0c;幾乎替代Listview和GridView的使用。但是分割線的實現&#xff0c;需要自己繼承ItemDecoration來繪制。 完整代碼已上傳至Github&#xff1a;RecyclerView實現九宮格效果 效果圖 item的布局文件 <?xml versi…

如何讀取指針指向的地址空間呢?

方法 使用%p 接收指針返回的地址空間 代碼 #include <stdio.h> #include <stdlib.h>int main() {int a 100;int *a_p &a;printf("%p\n",&a);//輸出&#xff1a;002AF744 輸出的是a變量的地址printf("%p\n",a_p);//輸出&#xff1…

科學究研明表,漢字序順并不一定影閱響讀

有個很有意思的現象&#xff1a; 不信你就來試試 中文打亂小工具 github地址&#xff1a;在線打亂文字順序

安卓EditText

常用屬性 android:textAllCaps"false"去除大寫狀態 inputType 常用 textpassword密碼 number數字 phone撥號鍵盤 設置光標位置 editText.setSelection(2);從1開始 editText.setSelection(1,3);從1開始,1–3中間部分,一個范圍

完善博文 共享內存一寫多讀無鎖實現的代碼邏輯部分

使用共享內存(內存映射)實現發布訂閱模式 多進程實現PubSub發布訂閱模式&#xff0c;從而實現進程間的通信。通信方式可以是TCP/UDP&#xff0c;管道Pipe/消息隊列&#xff0c;共享內存shared memory等等。其中TCP/UDP的方式是可以用作局域網以及跨平臺的通信&#xff0c;Pipe…

想對你說的話,就在這里!

甜(Tu)言(Wei)蜜(Qing)語(Hua)最近在github上看到了一個朋友開發的 土味情話在線生成器 &#xff0c;感覺還不錯&#xff0c;在這里推薦一下。 github地址&#xff1a;在線生成土味情話

linux讀寫文件 簡單版

代碼 //write void write_file(const std::string file_name){FILE *fp nullptr;fp fopen(file_name.c_str(),"w");fprintf(fp,"This is testing for mutex\n");fclose(fp); } //read void read_file(const std::string file_name){std::ifstream fp(fi…

具有中國風的傳統顏色(炫酷)

一個小小的中國風的傳統顏色&#xff0c;你覺得應該是什么樣子的呢&#xff1f; 看了下面這個&#xff0c;我一個搞移動開發的都想去搞前端開發了。 廢話不多說了&#xff0c;直接看效果&#xff1a; 訪問地址&#xff1a;中國傳統顏色手冊 github地址&#xff1a;Chinese…

Android Studio安裝問題及填坑

安裝過程 安裝Android Studio 其他問題 1.Android Studio出現Error:Unable to tunnel through proxy. Proxy returns “HTTP/1.1 400 Bad Request” 2.Could not resolve all artifacts for configuration :classpath 3.!No cached version of com.android.tools.build:gr…

Linux strtol將十六進制轉化為十進制

代碼 #include <iostream> #include "crypto_util.h"int get_file(const std::string file_name){size_t get_file_id 0;std::cout << hsm::common::get_md5_digest_hex(file_name) << std::endl;get_file_id strtol(reinterpret_cast<const…

Android WebView使用攻略

目錄前言一、簡介二、作用三、使用介紹1、Webview類常用方法1.1、加載url1.2、WebView的狀態1.3、關于前進 / 后退網頁1.4、清除緩存數據2、常用工具類2.1、WebSettings類2.2、WebViewClient類2.3、WebChromeClient類3、注意事項&#xff1a;如何避免WebView內存泄露&#xff1…

C++If與Switch語句

IF if語句不加括號就只是一個語句 舉例: int a5,b2; if(a)//按邏輯值來理解,0為假,其他為真,這里等價于a!0—>a為真時 ab; else ba; 計算三角形面積代碼 #include<iostream> #include<cmath>//數學公式庫 #include<iomanip> //格式控制 using namesp…

linux fork多進程 demo

注釋 使用系統調用fork()創建三個子進程&#xff1b;各個子進程顯示和輸出一些提示信息和自己的進程標識符&#xff1b;父進程顯示自己的進程ID和一些提示信息&#xff0c;然后調用waitpid()等待多個子進程結束&#xff0c;并在子進程結束后顯示輸出提示信息表示程序結束。 代…

Android WebView 與 JS 交互

目錄二、具體分析2.1 Android通過WebView調用 JS 代碼方式1&#xff1a;通過WebView的loadUrl()方式2&#xff1a;通過WebView的evaluateJavascript()方法對比使用建議2.2、JS通過WebView調用 Android 代碼2.2.1、方法分析方式1&#xff1a;通過 WebView的addJavascriptInterfa…

關于鎖的注意事項

文件鎖 Linux 提供了 fcntl 系統調用&#xff0c;可以鎖定文件但是文件鎖是和進程相關聯的&#xff0c;一個進程中的多個線程/協程對同一個文件進行的鎖操作會互相覆蓋掉&#xff0c;從而無效。fcntl 創建的鎖是建議性鎖&#xff0c;只有寫入的進程和讀取的進程都遵循建議才有效…