我正在尝试解决下一个问题:
有两种类型的功能。第一种类型可以同时从不同的线程执行(例如 - 从容器中读取数据)。第二个必须阻塞 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;
}