测试队列中等待condition_variables的多个线程

Testing multiple threads waiting on condition_variables in a queue

本文关键字:线程 variables 队列 等待 condition 测试      更新时间:2023-10-16

我正在测试如何推送队列中等待condition_variables的对象。我想按照我的意愿执行线程,因为它们稍后将出现在关键部分。线程中没有打印任何内容,可能出了什么问题?

mutex print_mu;
void print(function<void()> func)
{
lock_guard<mutex> lock(print_mu);
func();
}
unsigned int generate_id()
{
static unsigned int id = 1;
return id++;
}
class foo
{
unsigned int id_;
mutex mu_;
condition_variable cv_;
bool signal_;
bool& kill_;
public:
foo(bool kill) 
:kill_(kill) 
, signal_(false)
, id_(generate_id())
{
run();
}
void set()
{
signal_ = true;
}
void run()
{
async(launch::async, [=]()
{
unique_lock<mutex> lock(mu_);
cv_.wait(lock, [&]() { return signal_ || kill_ ; });
if (kill_)
{
print([=](){ cout << " Thread " << id_ << " killed!" << endl; });
return;
}
print([=](){ cout << " Hello from thread " << id_ << endl; });
});
}
};
int main()
{
queue<shared_ptr<foo>> foos;
bool kill = false;
for (int i = 1; i <= 10; i++)
{
shared_ptr<foo> p = make_shared<foo>(kill);
foos.push(p);
}
this_thread::sleep_for(chrono::seconds(2));
auto p1 = foos.front();
p1->set();
foos.pop();
auto p2 = foos.front();
p2->set();
foos.pop();
this_thread::sleep_for(chrono::seconds(2));
kill = true; // terminate all waiting threads unconditionally
this_thread::sleep_for(chrono::seconds(2));
print([=](){ cout << " Main thread exits" << endl; });
return 0;
}

当一个线程调用std::condition_variable::wait时,它将阻塞,直到另一个线程在同一个condition_variable上调用notify_onenotify_all。由于您从未在任何condition_variables上调用notify_*,因此它们将永远被阻止。

您的foo::run方法也将永远阻塞,因为std::future的析构函数将阻塞等待std::async调用的结果,如果它是引用该结果的最后一个std::future。因此,您的代码死锁:您的主线程被阻塞,等待异步未来完成,而异步未来被阻塞,等候主线程发出cv_信号。

(此外,foo::kill_是一个悬空引用。好吧,如果run无论如何都返回,它就会变成一个。)