C++11多读一写线程互斥锁

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19915152/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 23:15:17  来源:igfitidea点击:

C++11 multiple read and one write thread mutex

c++multithreadingc++11

提问by VSZM

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.

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

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:

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

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--;
}

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

这是在 C++11 中执行此操作的正确方法吗?

回答by aaronman

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.

非常接近,需要注意几件事,在 C++ 中,为了异常安全和可读性,IMO,使用 RAII 锁很好。你真正需要的是一个 shared_mutex,比如 boost 中或 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
}

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

如果您不想使用 boost @howardhinmant 可以提供一个参考实现的链接

回答by Casey

This is safe, but still likely not fair or performant:

这是安全的,但仍然可能不公平或性能不佳:

std::atomic<int> readers;
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.
    write.lock();
    readers++;
    write.unlock();

    // do read
    readers--;
}

A solution with condition variables could avoid busy waiting for readersto fall to 0, left as an exercise for the reader.

带有条件变量的解决方案可以避免忙于等待readers下降到 0,留给读者作为练习。