c ++互斥锁,不从内部阻止代码,但允许从外部阻止它

c++ mutexes that not blocks code from inside, but allow to block it from outside

我正在尝试解决下一个问题:

有两种类型的函数。第一种类型可以同时从不同的线程执行(例如 - 从容器中读取数据)。第二个必须阻塞第一种函数内的所有线程,直到完成某些操作(例如 - 更改容器)。

我相信这很容易,但我找不到解决方案。谁能帮帮我?

这是一个简单的例子。我希望线程每 3 秒停止输出 1 秒(我知道这段代码是不安全的(来自不同线程的 cout),但这只是一个简单的例子)

#include <iostream>
#include <thread>
#include <mutex>

using namespace std;


void f() {
    // TODO: wait if g() locked this
    cout << "Hello from thread " << this_thread::get_id() << endl;
    this_thread::sleep_for(100ms);
}

void g() {
    // TODO: some lock for f()
    cout << "All threads must sleep at night" << endl;
    this_thread::sleep_for(1000ms);
    // TODO: unlock
}

int main() {
    thread t1([]() { for (;;) f(); });
    thread t2([]() { for (;;) f(); });
    thread t3([]() { for (;;) f(); });

    for (;;) {
        this_thread::sleep_for(3000ms);
        g();
    }

    return 0;
}

这是一个常见的模式,最好使用 reader/writer 锁来解决。在 C++ 中,您想使用 std::shared_lock 并想象 f 是 reader 而 g 是作家。

声明变量:

std::shared_mutex mutex;

f中:

// Multiple threads can enter the shared lock (readers).
std::shared_lock lock(mutex);

g中:

// Only one thread can enter the unique lock (writers).
std::unique_lock lock(mutex);