滥用条件变量

Misuse of conditional variable

本文关键字:变量 条件      更新时间:2023-10-16

您能否查看并建议此代码有什么问题? 它要么在第 21 行崩溃 (cond_var_.wait(lock(; 在 gc_thread_proc((( 中,要么在第 56 行(lock.lock((; 在 release((( 中锁定。

#include <condition_variable>
#include <deque>
#include <functional>
#include <mutex>
#include <thread>
#include <vector>
#include <iostream>
class stream {
std::deque<int> pending_cleanups_;
std::mutex mut_{};
bool continue_{true};
std::thread gc_worker_;
std::condition_variable cond_var_;
void gc_thread_proc() {
while (true) {
std::vector<int> events_to_clean;
std::unique_lock<std::mutex> lock(mut_);
while (pending_cleanups_.empty() && continue_) {
cond_var_.wait(lock);
}
if (!continue_) {
break;
}
std::move(std::begin(pending_cleanups_), std::end(pending_cleanups_), std::back_inserter(events_to_clean));
pending_cleanups_.clear();
}
}

public:
explicit stream() : gc_worker_(&stream::gc_thread_proc, this) {}
void register_pending_event(int val) {
{
std::lock_guard<std::mutex> lock_guard(mut_);
pending_cleanups_.push_back(val);
}
cond_var_.notify_one();
}
void release() {
std::unique_lock<std::mutex> lock(mut_);
if (!continue_) {
return;
}
continue_ = false;
lock.unlock();
cond_var_.notify_one();
gc_worker_.join();
lock.lock();
pending_cleanups_.clear();
}
~stream() { release(); }
};

int main() {
int N=100000;
while(N--) {
std::cout << ".";
stream s;
}
std::cout << "ok";
return 0;
}

更改成员的顺序会使此问题消失 - 当cond_var_放在gc_worker_问题不会重现之前时。但我想它不能修复它只是以某种方式隐藏它......

非静态数据成员按类定义中的声明顺序初始化:https://en.cppreference.com/w/cpp/language/initializer_list

3) Then, non-static data members are initialized in order of declaration in the class definition.

在您的情况下,由于 std::thread 成员已初始化为在其构造函数中开始执行,因此在 gc_thread_proc 中使用 cv 时可能不会初始化。拥有 std::thread 成员的一种命令方法是在类构造器中移动分配它,即

class stream {
std::thread gc_worker_;
std::condition_variable cond_var_;
public:
stream(): {
gc_work = std::move(std::thread(&stream::gc_thread_proc, this));
}
};