线程安全的有界队列在 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 文件的调试版本。从本质上讲,在发布版本中,我链接到boost_thread-vc100-mt-gd-1_54.lib
但它应该链接到boost_thread-vc100-mt-1_54.lib
。
相关文章:
- 挂起和取消挂起一个文件DLL
- 如何防止C++遗留代码中的挂起指针
- 为什么所有C++编译器都会崩溃或挂起此代码
- 我编写了代码将十进制分数转换为其二进制等效数.它编译得很好,但在执行时挂起
- 构建挂起,即使是适度的文件大小
- 循环挂起迭代的 std::擦除 on std::list
- Poco::Net::FTPClientSession 在 open() 方法上挂起 129 秒,如果 ftp 主机不存
- Boost (Beast) websocket:同步写入挂起
- 程序在使用异步的 Boost.Process 调用 std::future.get() 后挂起
- UDP Boost ASIO 异步客户端挂起
- boost::asio::read函数挂起
- 线程安全的有界队列在 Boost 1.54 中挂起
- 正在关闭具有挂起的read_async_some的boost::asio::serial_port
- 当从matlab使用boost::线程时,挂起和/或段错误,而不是直接调用时
- 在Cygwin下使用Boost程序选项挂起
- 阻止取消Boost.Asio中挂起的异步操作
- 使用boost::process调用外部程序会导致调用程序挂起(Linux)
- Boost Asio async_read有时会在阅读时挂起,但并非总是如此
- Boost asio服务器挂起调用关闭Boost::套接字
- Boost::asio::acceptor在win7上挂起