對官方Mutexes的翻譯

參考鏈接

  • 參考鏈接

Mutexes

  • What's A Mutex?
  • Mutex Operations
  • Boost.Interprocess Mutex Types And Headers
  • Scoped lock
  • Anonymous mutex example
  • Named mutex example

What's A Mutex?

  • 互斥是相互排斥的意思,它是進程之間最基本的同步形式。互斥保證只有一個線程可以鎖定一個給定的互斥。如果一個代碼段被mutex鎖定和解鎖包圍,就會保證每次只有一個線程執行這段代碼。當該線程解鎖mutex時,其他線程可以進入到該代碼區域。
//The mutex has been previously constructedlock_the_mutex();//This code will be executed only by one thread
//at a time.unlock_the_mutex();
  • 互斥也可以是遞歸或非遞歸的。
  • 遞歸互斥可以由同一線程多次鎖定。為了完全解鎖互斥,該線程必須在鎖定它的同一時間解鎖該互斥。
  • 非遞歸mutexes不能被同一個線程鎖定多次。如果一個mutex被一個線程鎖定兩次,結果是未定義的,它可能會拋出一個錯誤,或者線程可能會被永遠阻塞

Mutex Operations

  • Boost.Interprocess的所有mutex類型都實現了以下操作。

void lock()

  • 效果。調用的線程試圖獲得mutex的所有權,如果另一個線程擁有mutex的所有權,它就等待,直到它能獲得所有權。如果一個線程獲得了mutex的所有權,則該線程必須解鎖mutex。如果mutex支持遞歸鎖定,則mutex必須被鎖定相同次數的線程解鎖。
  • 錯誤時拋出:interprocess_exception。

bool try_lock()

  • 效果。調用的線程試圖獲得mutex的所有權,如果另一個線程擁有mutex的所有權,則立即返回。如果mutex支持遞歸鎖定,則必須在鎖定相同次數的情況下解鎖mutex。
  • 返回。如果該線程獲得了mutex的所有權,返回true,如果另一個線程擁有mutex的所有權,返回false。
  • 錯誤時拋出:interprocess_exception。

bool timed_lock(const boost::posix_time::ptime &abs_time)

  • 效果。調用的線程如果能在規定的時間內取得對互換物的獨占權,就會設法取得。如果mutex支持遞歸鎖定,則必須在鎖定的相同次數內解鎖mutex。
  • 返回。如果線程獲得mutex的所有權,返回true,如果超時返回false。
  • 錯誤時拋出:interprocess_exception。

void unlock()

  • 先決條件。該線程必須擁有對mutex的獨占權。
  • 效果:調用線程釋放對mutex的獨占權。調用線程釋放了對mutex的獨占權。如果mutex支持遞歸鎖定,則mutex的解鎖次數必須與鎖定次數相同。
  • 拋出 錯誤時,由interprocess_exception派生出一個異常

Boost.Interprocess Mutex Types And Headers

Boost.Interprocess提供了以下Mutex類型。
#include <boost/interprocess/sync/interprocess_mutex.hpp>

  • interprocess_mutex: A non-recursive, anonymous mutex that can be placed in shared memory or memory mapped files.
  • interprocess_mutex.一個非遞歸、匿名的mutex,可以放在共享內存或內存映射文件中。一個非遞歸、匿名的mutex,可以放在共享內存或內存映射文件中。
  • #include <boost/interprocess/sync/interprocess_recursive_mutex.hpp>
  • interprocess_recursive_mutex: A recursive, anonymous mutex that can be placed in shared memory or memory mapped files.
  • #include <boost/interprocess/sync/named_mutex.hpp>
  • named_mutex: A non-recursive, named mutex.
  • #include <boost/interprocess/sync/named_recursive_mutex.hpp>
  • named_recursive_mutex: A recursive, named mutex.

Scoped lock

  • 在進程讀取或寫入數據后解鎖一個mutex是非常重要的。在處理異常時,這可能是很困難的,所以通常mutexes是和范圍鎖一起使用的,這個類可以保證mutex即使在異常發生時也會被解鎖。要使用作用域鎖,只需包含。
  • 基本上,一個作用域鎖在它的析構器中調用unlock(),而一個mutex總是在發生異常時被解鎖。范圍鎖有很多構造函數來鎖定、try_lock、timed_lock一個mutex或者根本不鎖定它。
  • #include <boost/interprocess/sync/scoped_lock.hpp>
using namespace boost::interprocess;//Let's create any mutex type:
MutexType mutex;{//This will lock the mutexscoped_lock<MutexType> lock(mutex);//Some code//The mutex will be unlocked here
}{//This will try_lock the mutexscoped_lock<MutexType> lock(mutex, try_to_lock);//Check if the mutex has been successfully lockedif(lock){//Some code}//If the mutex was locked it will be unlocked
}{boost::posix_time::ptime abs_time = ...//This will timed_lock the mutexscoped_lock<MutexType> lock(mutex, abs_time);//Check if the mutex has been successfully lockedif(lock){//Some code}//If the mutex was locked it will be unlocked
}
  • For more information, check the?scoped_lock's reference.

Anonymous mutex example

  • 想象一下,兩個進程需要向建立在共享內存中的循環緩沖區寫入軌跡。每個進程都需要獲得對循環緩沖區的獨占訪問權,寫入軌跡并繼續。
  • 為了保護循環緩沖區,我們可以在循環緩沖區中存儲一個進程共享互斥。每個進程在寫數據之前會鎖定mutex,并在結束寫軌跡時寫一個標志(doc_anonymous_mutex_shared_data.hpp頭)。

doc_anonymous_mutex_shared_data.hpp

#include <boost/interprocess/sync/interprocess_mutex.hpp>struct shared_memory_log
{enum { NumItems = 100 };enum { LineSize = 100 };shared_memory_log():  current_line(0),  end_a(false),  end_b(false){}//Mutex to protect access to the queueboost::interprocess::interprocess_mutex mutex;//Items to fillchar   items[NumItems][LineSize];int    current_line;bool   end_a;bool   end_b;
};
  • 這是進程主進程。創建共享內存,構建循環緩沖區,并開始寫軌跡。
#include <boost/interprocess/shared_memory_object.hpp>
#include <boost/interprocess/mapped_region.hpp>
#include <boost/interprocess/sync/scoped_lock.hpp>
#include "doc_anonymous_mutex_shared_data.hpp"
#include <iostream>
#include <cstdio>using namespace boost::interprocess;int main ()
{try{//Remove shared memory on construction and destructionstruct shm_remove{shm_remove() { shared_memory_object::remove("MySharedMemory"); }~shm_remove(){ shared_memory_object::remove("MySharedMemory"); }} remover;//Create a shared memory object.shared_memory_object shm(create_only               //only create,"MySharedMemory"          //name,read_write   //read-write mode);//Set sizeshm.truncate(sizeof(shared_memory_log));//Map the whole shared memory in this processmapped_region region(shm                       //What to map,read_write   //Map it as read-write);//Get the address of the mapped regionvoid * addr       = region.get_address();//Construct the shared structure in memoryshared_memory_log * data = new (addr) shared_memory_log;//Write some logsfor(int i = 0; i < shared_memory_log::NumItems; ++i){//Lock the mutexscoped_lock<interprocess_mutex> lock(data->mutex);std::sprintf(data->items[(data->current_line++) % shared_memory_log::NumItems],"%s_%d", "process_a", i);if(i == (shared_memory_log::NumItems-1))data->end_a = true;//Mutex is released here}//Wait until the other process endswhile(1){scoped_lock<interprocess_mutex> lock(data->mutex);if(data->end_b)break;}}catch(interprocess_exception &ex){std::cout << ex.what() << std::endl;return 1;}return 0;
}
  • 第二個進程打開共享內存,獲得對循環緩沖區的訪問權,并開始寫入痕跡。
#include <boost/interprocess/shared_memory_object.hpp>
#include <boost/interprocess/mapped_region.hpp>
#include <boost/interprocess/sync/scoped_lock.hpp>
#include "../include/doc_anonymous_mutex_shared_data.hpp"
#include <iostream>
#include <cstdio>using namespace boost::interprocess;int main ()
{//Remove shared memory on destructionstruct shm_remove{~shm_remove(){ shared_memory_object::remove("MySharedMemory"); }} remover;//Open the shared memory object.shared_memory_object shm(open_only                    //only create,"MySharedMemory"              //name,read_write  //read-write mode);//Map the whole shared memory in this processmapped_region region(shm                       //What to map,read_write //Map it as read-write);//Get the address of the mapped regionvoid * addr       = region.get_address();//Construct the shared structure in memoryshared_memory_log * data = static_cast<shared_memory_log*>(addr);//Write some logsfor(int i = 0; i < 100; ++i){//Lock the mutexscoped_lock<interprocess_mutex> lock(data->mutex);std::sprintf(data->items[(data->current_line++) % shared_memory_log::NumItems],"%s_%d", "process_a", i);if(i == (shared_memory_log::NumItems-1))data->end_b = true;//Mutex is released here}//Wait until the other process endswhile(1){scoped_lock<interprocess_mutex> lock(data->mutex);if(data->end_a)break;}return 0;
}
  • 正如我們所看到的那樣,mutex對于保護數據是有用的,但不是用來通知事件到另一個進程。為此,我們需要一個條件變量,我們將在下一節中看到。

Named mutex example

  • 現在想象一下,有兩個進程想要向一個文件寫入跟蹤信息。首先他們寫下自己的名字,然后寫下消息。由于操作系統可以在任何時刻中斷一個進程,我們可以混合兩個進程的部分消息,所以我們需要一種方法將整個消息原子地寫入文件。為了達到這個目的,我們可以使用一個命名的mutex,這樣每個進程在寫之前都會鎖定mutex。

#include <boost/interprocess/sync/scoped_lock.hpp>
#include <boost/interprocess/sync/named_mutex.hpp>
#include <fstream>
#include <iostream>
#include <cstdio>int main ()
{using namespace boost::interprocess;try{struct file_remove{file_remove() { std::remove("file_name"); }~file_remove(){ std::remove("file_name"); }} file_remover;struct mutex_remove{mutex_remove() { named_mutex::remove("fstream_named_mutex"); }~mutex_remove(){ named_mutex::remove("fstream_named_mutex"); }} remover;//Open or create the named mutexnamed_mutex mutex(open_or_create, "fstream_named_mutex");std::ofstream file("file_name");for(int i = 0; i < 10; ++i){//Do some operations...//Write to file atomicallyscoped_lock<named_mutex> lock(mutex);file << "Process name, ";file << "This is iteration #" << i;file << std::endl;}}catch(interprocess_exception &ex){std::cout << ex.what() << std::endl;return 1;}return 0;
}

?

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

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

相關文章

計算機應用基礎

計算概論知識點 1.計算機之父&#xff1a;馮.諾伊曼 計算機基本組成&#xff1a;運算器&#xff0c;控制器&#xff0c;存儲器&#xff0c;輸入設備&#xff0c;輸出設備 2.幾種計算機&#xff1a;臺式計算機,筆記本式計算機,PC服務器,平板式計算機… 3.電腦的硬件&#xff1a;…

Android最全UI庫合集

目錄抽屜菜單ListViewWebViewSwitchButton按鈕點贊按鈕進度條TabLayout圖標下拉刷新ViewPager圖表(Chart)菜單(Menu)浮動菜單對話框空白頁滑動刪除手勢操作RecyclerViewCardColorDrawableSpinner布局模糊效果TabBarAppBar選擇器(Picker)跑馬燈日歷時間主題樣式ImageView通知聊天…

對于boost鎖機制結論性的介紹

Conditions Whats A Condition Variable?Boost.Interprocess Condition Types And HeadersAnonymous condition example Whats A Condition Variable? 在前面的例子中&#xff0c;一個mutex被用來鎖定&#xff0c;但我們不能用它來有效地等待&#xff0c;直到滿足繼續的條件…

C++數據類型

C 數據類型 |–基本數據類型: 整型 short短整型 2 int基本整型4 long長整型 8 浮點型 float單精度型 4 double雙精度型 8 long double長雙精度型 16 字符型 char 1 邏輯型 bool 1 空類型 void |–構造類型 數組類型 構造體類型 struct 共用體類型 union 枚舉類型 enum 類類型…

Android Gradle 多渠道打包、動態配置AppName

目錄一、簡介二、Gradle多渠道打包1、普通做法2、Gradle多渠道打包一、簡介 因為國內Android應用分發市場的現狀&#xff0c;我們在發布APP時&#xff0c;一般需要生成多個渠道包&#xff0c;上傳到不同的應用市場。這些渠道包需要包含不同的渠道信息&#xff0c;在APP和后臺交…

boost鎖機制中Semaphores的介紹

結構 Whats A Semaphore?Boost.Interprocess Semaphore Types And HeadersAnonymous semaphore example Whats A Semaphore? 旗語是一種基于內部計數的進程間同步機制&#xff0c;它提供了兩種基本操作。等待&#xff1a;測試旗語數的值&#xff0c;如果小于或等于0&#x…

Android Gradle 批量修改生成的apk文件名

目錄一、簡介二、代碼實現1、 Gradle 3.0以下版本2、Gradle 3.0以上版本一、簡介 平時開發都知道&#xff0c;我們要上線的時候需要在Android studio打包apk文件&#xff0c;可是默認的打包名是app-release.apk或者app-debug.apk這樣的名字&#xff0c;太沒有辨識度了。 下面…

C++boost Class named_condition翻譯

Class named_condition boost::interprocess::named_condition 簡介 // In header: <boost/interprocess/sync/named_condition.hpp>class named_condition { public:// construct/copy/destructnamed_condition(create_only_t, const char *, const permissions &…

Android Studio 代理設置以及代理完全清除

目錄一、代理設置二、代理完全清除一、代理設置 首先我們來看下怎樣設置代理&#xff0c;Mac下打開【Preferences…】&#xff0c;然后搜索"HTTP"&#xff0c;選擇【HTTP Proxy】&#xff0c;按圖中設置配置好后&#xff0c;點擊【Apply】&#xff0c;然后在點擊【O…

安卓布局位置,dp與px的區別

手機6寸—指對角線 布局位置 橫軸—x軸 縱軸—y軸 一個像素點 dp與Px dp:設備無關像素,與像素密度相關,像素距離 dpi:像素密度,每英寸包含的像素數 px:屏幕上一個物理像素點 ldpi低密度 1dp0.75px mdpi中密度 1dp1px hdpi高密度 1dp1.5px xhdpi超高密度 1dp2px xxhdpi超…

Android Studio 快捷鍵大全(Mac系統)

目錄一、Mac上的按鍵符號二、快捷鍵查找/查看相關控制操作相關代碼重構相關一、Mac上的按鍵符號 符號說明?option / alt?shift?control?command?esc 二、快捷鍵 查找/查看相關 快捷鍵說明雙擊 shift搜索任意內容command F / command R當前文件查找/替換&#xff0c;使…

ubuntu下clion軟件連接boost庫文件

整體配置 cmake_minimum_required(VERSION 3.17) project(mutex_learn)set(CMAKE_CXX_STANDARD 14) #boost庫所在的根目錄set(BOOST_ROOT "/usr/local/include/boost") #添加頭文件搜索路徑 include_directories(/usr/local/include) #添加庫文件搜索路徑 link_dir…

Android程序結構

Project方式 .gradle文件夾:編譯相關生成 .idea文件夾:idea生成 app文件夾----應用程序的源代碼和資源 build----編譯后的文件存放的位置,最終apk文件存放的位置 libs:存放.jar和.so文件 src:AndroidTest與test存放測試相關的內容 main中Java文件夾存放Java源碼,res文件…

通過Github創建Android庫供其他項目依賴引用

目錄一、簡介二、實現第一步&#xff1a;將自己的項目托管到Github上。第二步&#xff1a;點擊releases。第三步&#xff1a;創建release。第四步&#xff1a;填寫版本號、名稱、描述信息。第五步&#xff1a;點擊【Publish release】。第六步&#xff1a;復制項目路徑。第七步…

使用boost模板函數實現讀寫鎖

介紹 shared_mutex即讀寫鎖&#xff0c;不同與我們常用的獨占式鎖mutex&#xff0c;shared_mutex是共享與獨占共存的鎖&#xff0c;實現了讀寫鎖的機制&#xff0c;即多個讀線程一個寫線程&#xff0c;通常用于對于一個共享區域的讀操作比較頻繁&#xff0c;而寫操作比較少的情…

安卓內邊距padding與外邊距magrin

內邊距padding與外邊距margin 內邊距只有容器才有,即里面要有視圖 具體示例

Android Studio發布項目到jcenter

目錄一、創建Bintray賬戶及Maven倉庫二、上傳項目到jcenter1、配置Android項目2、Gradle命令上傳3、在項目中引用4、Add to JCenter三、Demo示例一、創建Bintray賬戶及Maven倉庫 1、打開Bintray首頁&#xff0c;點擊 For an Open Source Account &#xff0c;快速注冊或者用第…

C++讀取文件,將文件內容讀到string字符串里面

使用stringstream和ifstream實現 代碼 std::ifstream f{file_name, std::ios::binary};std::stringstream ss;ss << f.rdbuf();auto data ss.str();

Android MotionEvent中getX()、getRawX()和getTop()的區別

為了展示getX()、getRawX()和getTop()方法的區別&#xff0c;我們寫了一個簡單的測試Demo&#xff0c;我們寫了一個自定義控件&#xff08;繼承ImageView&#xff09;。 package com.demo.ui;import android.content.Context; import android.support.annotation.Nullable; im…