gpt4 book ai didi

c++ - boost 条件不适用于具有两个生产者和一个消费者的线程安全队列

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:23:45 24 4
gpt4 key购买 nike

我有两个线程添加到“线程安全”队列中。但是,当第二个线程尝试“推送”内容时。不会通知消费者内容可用。队列继续增长,但 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

此代码在使用 boost 1.51.0 的 Fedora 14 中确实有效,但在 Windows 7 中的 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 似乎没有使用 -pthread/-mthreads。如果您不要求编译器生成多线程代码,通常不要指望您的代码能够正常工作。

关于c++ - boost 条件不适用于具有两个生产者和一个消费者的线程安全队列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14842467/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com