为什么std :: queue不是线程安全的?

net*_*tik 7 c++ queue multithreading

话题说明了这一点.我不明白为什么std :: queue(或者通常:任何队列)本质上不是线程安全的,当没有涉及其他数据结构的迭代器时.

根据共同的规则

  • 至少有一个主题是写...
  • 另一个线程正在从共享资源中读取

我应该在以下示例代码中遇到冲突:

#include "stdafx.h"
#include <queue>
#include <thread>
#include <iostream>

struct response
{
    static int & getCount()
    {
        static int theCount = 0;
        return theCount;
    }

    int id;
};


std::queue<response> queue;

// generate 100 response objects and push them into the queue
void produce()
{
    for (int i = 0; i < 100; i++)
    {
        response r; 
        r.id = response::getCount()++;
        queue.push(r);
        std::cout << "produced: " << r.id << std::endl;
    }
}

// get the 100 first responses from the queue
void consume()
{
    int consumedCounter = 0;
    for (;;)
    {       
        if (!queue.empty())
        {
            std::cout << "consumed: " << queue.front().id << std::endl;
            queue.pop();
            consumedCounter++;
        }

        if (consumedCounter == 100)
            break;
    }
}

int _tmain(int argc, _TCHAR* argv[])
{

    std::thread t1(produce);
    std::thread t2(consume);

    t1.join();
    t2.join();

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

一切似乎都运行正常: - 没有违反完整性/数据损坏 - 消费者获取它们的元素的顺序是正确的(0 <1 <2 <3 <4 ...),当然是顺序刺.和利弊.打印是随机的,因为没有涉及信令.

use*_*875 19

想象一下,你检查!queue.empty(),输入下一个块,然后在访问之前queue.first(),另一个线程将删除(弹出)唯一的元素,因此你查询一个空队列.

使用如下所示的同步队列

#pragma once

#include <queue>
#include <mutex>
#include <condition_variable>

    template <typename T>
    class SharedQueue
    {
    public:
        SharedQueue();
        ~SharedQueue();

        T& front();
        void pop_front();

        void push_back(const T& item);
        void push_back(T&& item);

        int size();
        bool empty();

    private:
        std::deque<T> queue_;
        std::mutex mutex_;
        std::condition_variable cond_;
    }; 

    template <typename T>
    SharedQueue<T>::SharedQueue(){}

    template <typename T>
    SharedQueue<T>::~SharedQueue(){}

    template <typename T>
    T& SharedQueue<T>::front()
    {
        std::unique_lock<std::mutex> mlock(mutex_);
        while (queue_.empty())
        {
            cond_.wait(mlock);
        }
        return queue_.front();
    }

    template <typename T>
    void SharedQueue<T>::pop_front()
    {
        std::unique_lock<std::mutex> mlock(mutex_);
        while (queue_.empty())
        {
            cond_.wait(mlock);
        }
        queue_.pop_front();
    }     

    template <typename T>
    void SharedQueue<T>::push_back(const T& item)
    {
        std::unique_lock<std::mutex> mlock(mutex_);
        queue_.push_back(item);
        mlock.unlock();     // unlock before notificiation to minimize mutex con
        cond_.notify_one(); // notify one waiting thread

    }

    template <typename T>
    void SharedQueue<T>::push_back(T&& item)
    {
        std::unique_lock<std::mutex> mlock(mutex_);
        queue_.push_back(std::move(item));
        mlock.unlock();     // unlock before notificiation to minimize mutex con
        cond_.notify_one(); // notify one waiting thread

    }

    template <typename T>
    int SharedQueue<T>::size()
    {
        std::unique_lock<std::mutex> mlock(mutex_);
        int size = queue_.size();
        mlock.unlock();
        return size;
    }
Run Code Online (Sandbox Code Playgroud)

调用front()等待它有一个元素并锁定底层队列,这样一次只有一个线程可以访问它.

  • `front()` 实现了一个有漏洞的抽象。它返回对私有容器的引用,但不执行任何保护元素的操作。如果线程 A 调用“front()”并且线程 B 调用“pop_front()”,事情看起来就不那么好了。引用是一种责任。代码忽略了这一点。 (3认同)
  • 我喜欢你的实现,我想我会我们这个。但是在您的解释中,您假设有多个消费者。他只有一个消费者,所以没有人会调用 empty、first 或 pop。在最坏的情况下,他可以在两者之间进行推动 (2认同)
  • 您也不能将“pop”和“pop_front”分开。线程 A 和 B 可以先分别调用“front”,然后再调用“pop_front”。然后,您对一个元素进行了两次处理,而一个则根本没有处理。 (2认同)