对官方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.mzph.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…