错误使用条件变量

时间:2020-01-22 17:04:41

标签: c++ multithreading

能否请您查看并提出此代码有什么问题? 它要么在第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_问题不会重现之前。但是我想它并不能解决问题,只是以某种方式将其隐藏了...

1 个答案:

答案 0 :(得分:3)

非静态数据成员按照类定义中的声明顺序初始化: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时可能不会初始化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));
  }
};
相关问题