C ++ 11多读和一写线程互斥 [英] C++11 multiple read and one write thread mutex

查看:153
本文介绍了C ++ 11多读和一写线程互斥的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个应用程序,其中一些STL容器读取3个线程,并写成2.我知道有TBB的多线程容器,但它不是我的应用程序的一个选项。

I have an application, where some STL containers are read in 3 threads, and written in 2. I know there is TBB for multi-threaded containers, but it is not an option in my application.

所以我想使程序线程安全使用std :: mutex和我的双手。这是我做的一个简单版本:

So I want to make the program thread-safe using std::mutex and my bare hands. This is a simple version of what I did:

int readers = 0;
std::mutex write;

// One write, no reads.
void write_fun()
{
    write.lock();// We lock the resource
    while(readers > 0){}// We wait till everyone finishes read.
    // DO WRITE
    write.unlock();// Release
}

// Multiple reads, no write
void read_fun()
{
    // We wait if it is being written.
    while(!write.try_lock()){}
    write.unlock();

    readers++;
    // do read
    readers--;
}

这是在C ++ 11中正确的方法吗? p>

Is this the correct way to do this in C++11?

推荐答案

很接近,耦合的事情要注意,在c ++中的异常安全和可读性,IMO,你真正需要的是一个shared_mutex喜欢在boost或来自c ++ 14。

Pretty close, couple things to note, in c++ for exception safety and readability, IMO, it is good to use RAII locks. What you really need is a shared_mutex like in boost or coming in c++14.

std::shared_mutex write; //use boost's or c++14 

// One write, no reads.
void write_fun()
{
    std::lock_guard<std::shared_mutex> lock(write);
    // DO WRITE
}

// Multiple reads, no write
void read_fun()
{
    std::shared_lock<std::shared_mutex> lock(write);
    // do read
}

如果您不想使用boost @howardhinmant是做了一个链接到一个参考实施

If you don't want to use boost @howardhinmant was do kind as to give a link to a reference implementation

这篇关于C ++ 11多读和一写线程互斥的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆