当我试图唤醒另一个线程时,我遇到了一个问题。一个简单的生产者/消费者的东西。
代码下方。第 85 行是我不明白为什么它不起作用的地方。生产者线程填满一个 std::queue 并调用 std::condition_variable.notify_one(),而消费者线程正在等待 NOT std::queue.empty()。
提前感谢您的帮助
#include <mutex>
#include <condition_variable>
#include <queue>
#include <string>
#include <iostream>
#include <thread>
// request
class request :
public std::mutex,
public std::condition_variable,
public std::queue<std::string>
{
public:
virtual ~request();
};
request::~request()
{
}
// producer
class producer
{
public:
producer(request &);
virtual ~producer();
void operator()();
private:
request & request_;
};
producer::producer(request & _request)
:
request_(_request)
{
}
producer::~producer()
{
}
void
producer::operator()()
{
while (true) {
std::lock_guard<std::mutex> lock(request_);
std::cout << "producer\n";
request_.push("something");
std::this_thread::sleep_for(std::chrono::seconds(1));
request_.notify_one();
}
}
class consumer
{
public:
consumer(request &);
virtual ~consumer();
void operator()();
private:
request & request_;
};
consumer::consumer(request & _request)
:
request_(_request)
{
}
consumer::~consumer()
{
}
void
consumer::operator()()
{
while (true) {
std::unique_lock<std::mutex> lock(request_); // <-- the problem
std::cout << "consumer\n";
request_.wait (
lock, [this] {return !request_.empty();}
);
request_.pop();
}
}
int
main()
{
// request
request request_;
// producer
std::thread producer_{producer(request_)};
// consumer
std::thread first_consumer_{consumer(request_)};
std::thread second_consumer_{consumer(request_)};
// join
producer_.join();
first_consumer_.join();
second_consumer_.join();
}