为什么我的condition_variable失败?

时间:2018-07-01 02:40:45

标签: c++ condition-variable

我在C ++ 11中具有以下消费者/生产者应用程序。但是,这会导致死锁:

queue_cond_var->wait(locker)

producer()根据需要运行, main()在该行处于死锁状态:

consumer_thread.join();

它正在OS X Xcode 9.4上运行。

这是我的代码:

static void consumer(condition_variable *queue_cond_var,
                     queue<int> &shared_queue, bool &notified,
                     bool *finished, mutex *queue_m) {
    while (!*finished) {
        unique_lock<mutex> locker(*queue_m);
        while (!notified)
            queue_cond_var->wait(locker);
        while (!shared_queue.empty())
            cout << shared_queue.front() << " ", shared_queue.pop();
        notified = false;
    }
}

int main() {
    mutex queue_m;
    condition_variable queue_cond_var;
    queue<int> shared_queue;
    bool notified, finished = false;
    vector<thread> threads;
    thread consumer_thread(consumer, &queue_cond_var, ref(shared_queue),
                           ref(notified), &finished, &queue_m);
    for (int i = 0; i < 5; i++)
        threads.push_back(thread(producer, ref(shared_queue), ref(notified),
                                 &queue_cond_var, &queue_m));
    for(auto &t:threads)
        t.join();
    finished = true;
    queue_cond_var.notify_one();
    consumer_thread.join();
}

0 个答案:

没有答案
相关问题