Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

does Qt have a thread-safe Queue?



  • does Qt have a thread-safe Queue?
    thanks



  • unless something has changed in recent versions you need to manage queue access using a semaphore.



  • #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;
        }
    


  • found this one at stackoverflow


  • Lifetime Qt Champion

    @opengpu said in does Qt have a thread-safe Queue?:

    found this one at stackoverflow

    Then you should also provide the link to the stack overflow post that has that code in it.

    Just in case, Qt also provides all the building blocks to implement a shared queue in a similar way.


Log in to reply