boost条件不在具有两个生产者和一个消费者的线程安全队列上工作
boost conditional not working on thread safe queue with two producers and one consumer
我有两个线程添加到"线程安全"队列中。但是,当第二个线程尝试"推送"内容时。不会通知消费者内容可用。队列继续增长,但notify_one()从未通知消费方法中的条件。为什么会这样?
#ifndef CONCURRENT_QUEUE_H
#define CONCURRENT_QUEUE_H
#include <queue>
#include <boost/thread.hpp>
template<typename Data>
class concurrent_queue {
private:
std::queue<Data> the_queue;
mutable boost::mutex the_mutex;
boost::condition_variable the_condition_variable;
public:
void push(Data const& data) {
boost::mutex::scoped_lock lock(the_mutex);
the_queue.push(data);
lock.unlock();
the_condition_variable.notify_one();
}
void wait_and_pop(Data& popped_value) {
boost::mutex::scoped_lock lock(the_mutex);
while(the_queue.empty()) {
the_condition_variable.wait(lock);
}
popped_value=the_queue.front();
the_queue.pop();
}
};
#endif
这段代码在Fedora 14中使用boost 1.51.0确实有效,但在Windows7中的boost 1.50.0中不起作用。
INCLUDEPATH +=
.
/home/mehoggan/Devel/x86-fps/boost_1_50_0/include
LDFLAGS += -Wl,-rpath=/home/mehoggan/Devel/x86-fps/boost_1_50_0/lib
LIBS +=
-L/home/mehoggan/Devel/x86-fps/boost_1_50_0/lib
-lboost_system
-lboost_thread
-lz
#ifndef CONCURRENT_QUEUE_H
#define CONCURRENT_QUEUE_H
#include <queue>
#include <boost/thread.hpp> // Using boost 1.50.0
template<typename Data>
class concurrent_queue {
private:
std::queue<Data> the_queue;
mutable boost::mutex the_mutex;
boost::condition_variable the_condition_variable;
public:
void push(Data const& data) {
boost::mutex::scoped_lock lock(the_mutex);
the_queue.push(data);
lock.unlock();
the_condition_variable.notify_all();
}
void wait_and_pop(Data& popped_value) {
boost::mutex::scoped_lock lock(the_mutex);
while(the_queue.empty()) {
the_condition_variable.wait(lock);
}
popped_value=the_queue.front();
the_queue.pop();
}
};
#endif
concurrent_queue<int> the_queue;
void thread1func() {
do {
the_queue.push(1);
} while (true);
}
void thread2func() {
do {
the_queue.push(2);
} while (true);
}
void thread3func() {
do {
int read;
the_queue.wait_and_pop(read);
std::cout << "I read from thread " << read << std::endl;
} while (true);
}
int main(int argc, char *argv[]) {
boost::thread thread1 = boost::thread(thread1func);
boost::thread thread2 = boost::thread(thread2func);
boost::thread thread3 = boost::thread(thread3func);
thread1.join();
thread2.join();
thread3.join();
}
您的Makefile似乎没有使用-phread/-mthreads。一般来说,如果你不要求编译器生成多线程代码,就不要指望你的代码能正常工作。
相关文章:
- 如何创建一个CMake变量,除非显式重写,否则使用默认值
- 删除一个线程上有数百万个字符串的大型哈希映射会影响另一个线程的性能
- 为什么两个不同的未命名名称空间可以共存于一个cpp文件中
- 运行同一解决方案的另一个项目的项目
- 挂起和取消挂起一个文件DLL
- 用C++中的一个变量定义一个常量
- 函数向量_指针有不同的原型,我可以构建一个吗
- 在c++中用vector填充一个简单的动态数组
- 如何在选项卡视图Qt中设置一个新项目,并保存以前的项目
- 预处理器:插入结构名称中的前一个行号
- 我在c++代码中生成了一个运行时#3异常
- 我想将一个对T类型的非常量左值引用绑定到一个T类型的临时值
- 从链接列表c++中删除一个项目
- 线程安全FIFO/队列(多个生产者,一个消费者)
- 一个生产者,两个消费者对生产者生产的'queue'采取行动
- 在c++中实现一个多生产者/消费者无锁队列
- 在一个简单的c++ 11四线程程序中,如果我注释标准输出打印行,我的两个消费者线程就不会返回
- 在像LMAX破坏者这样的模式中,你如何处理一个缓慢的消费者
- boost条件不在具有两个生产者和一个消费者的线程安全队列上工作
- 为什么我收到一个简单的提升生产者/消费者计划的锁定断言失败