c++ - 线程安全有界队列在 Boost 1.54 中挂起

标签 c++ multithreading boost boost-thread

以下用于有界线程安全队列的代码曾经在 Boost 1.49 中按预期工作。但是,在更新到 Boost 1.54 后,代码不再按预期运行。即,当缓冲区为空(已满)时,消费者线程(生产者线程)永远等待 m_not_empty (m_not_full) 条件变量并且永远不会醒来(我认为是因为生产者线程没有互斥锁)。

1.54 版中是否有一些可能破坏代码的更改?或者,也许我遗漏了代码中的错误?

#include <iostream>
#include <boost/circular_buffer.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/thread/condition.hpp>
#include <boost/thread/thread.hpp>

template <class T>
class bounded_buffer {
public:
    bounded_buffer(size_t capacity) {cb.set_capacity(capacity);}
    void push(T item) {
        boost::mutex::scoped_lock lock(m_mutex);
        while (cb.full()) {
            m_not_full.wait(lock);
        }
        cb.push_back(item);
        lock.unlock();
        m_not_empty.notify_one();
    }

    void pop(T &pItem) {
        boost::mutex::scoped_lock lock(m_mutex);
        while (cb.empty()) {
            m_not_empty.wait(lock);
        }
        pItem = cb.front();
        cb.pop_front(); 
        lock.unlock();
        m_not_full.notify_one();
    }

private:     
    boost::mutex m_mutex;
    boost::condition m_not_empty;
    boost::condition m_not_full;
    boost::circular_buffer<T> cb;
};

bounded_buffer<int> bb_int(4);

void producer() {
    int i = 10;
    for(int j=0; j<100; ++j) {
        bb_int.push(i);
        std::cout << "producer: " << i << std::endl;
        i++;
    }
}

void consumer() {
    int i;
    for(int j=0; j<100; ++j) {
        bb_int.pop(i);
        std::cout << "consumer: " << i << std::endl;
    }
}

// Test code
int main() {
    // Start the threads.
    boost::thread consume(consumer);
    boost::thread produce(producer);

    // Wait for completion.
    consume.join();
    produce.join();
}

最佳答案

好的,我发现了一个错误。我在发布版本中编译了代码,但链接到 .lib 文件的调试版本。本质上,在发布版本中我链接到 boost_thread-vc100-mt-gd-1_54.lib 但它应该链接到 boost_thread-vc100-mt-1_54.lib

关于c++ - 线程安全有界队列在 Boost 1.54 中挂起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19281232/

相关文章:

C++:使用 C++14 通用 lambda boost fusion fold

java - undefined symbol 错误

c++ - QWinTaskbarProgress 我做错了什么?

c++ - 在 C++ 中将值推回 vector 的函数

c++ - 从主线程 c++11 执行函数调用的线程

c++ - 清除包括换行符的输入缓冲区

c# - 使用 C# 替换 native .exe 中的字符串

python - 如何测试访问数据库的其他线程

java - Android 上的应用程序重新启动后,线程才会启动

linux - 尝试静态链接 Boost