参考链接
- 参考链接
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;
}