簡體   English   中英

線程安全的有界隊列在Boost 1.54中掛起

[英]Thread-safe bounded queue hangs in Boost 1.54

以下用於有界線程安全隊列的代碼用於在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文件的調試版本。 本質上,在發布版本I中鏈接到boost_thread-vc100-mt-gd-1_54.lib但它應該鏈接到boost_thread-vc100-mt-1_54.lib

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM