Код: Выделить всё
class SafeQueue
{
private:
std::queue data_queue;
mutable std::mutex m;
std::condition_variable cv;
std::atomic flag{ true }; // Atomic flag to control the queue
public:
void push(int val)
{
std::lock_guard lock(m);
data_queue.push(val);
cv.notify_one(); // Notify waiting thread upon pushing data
}
bool pop(int& val)
{
std::unique_lock lock(m);
cv.wait(lock, [this]() { return !data_queue.empty() || !flag; }); // Wait until queue is not empty or flag is turned off
if (!flag && data_queue.empty())
{
return false; // Queue is empty and flag is off, return false to indicate termination
}
if (!data_queue.empty())
{
val = data_queue.front();
data_queue.pop();
return true;
}
return false;
}
void turnOff()
{
flag = false;
}
bool isFlagOn() const
{
return flag;
}
};
void consumerLoop(SafeQueue& q)
{
while (q.isFlagOn())
{
int val;
if (q.pop(val))
{
std::cout
Подробнее здесь: [url]https://stackoverflow.com/questions/78296766/deadlock-on-condition-variable-example[/url]