0

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

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

我确信这是一项简单的任务,但我找不到解决方案。谁能帮帮我吗?

这是一个简单的例子。我希望线程每 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;
}
4

1 回答 1

1

这是使用读/写锁最好解决的常见模式。在 C++ 中,您想使用std::shared_lock并想象它既f是读者又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);
于 2021-05-23T20:25:06.583 回答