參考鏈接
- 參考鏈接
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;
}
?