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

QList thread safety



  • hello, I have a question about thread-safety as I want to use a QList across multiple threads. Normally you would use a QMutex for this, but I dont want to have to create a new QMutex object for every list I want to use and call lock/unlock manually at each place, so I had the idea to make my own "List" class which uses QList.

    This is the code:

    template <class T>
    class ThreadSafeList
    {
    public:
        ThreadSafeList();
    
        void append(const T &value)
        {
            mutex.lock();
            list.append(value);
            mutex.unlock();
        }
    
        void removeAt(int i)
        {
            mutex.lock();
            list.removeAt(i);
            mutex.unlock();
        }
    
        int count()
        {
            mutex.lock();
            int count = list.count();
            mutex.unlock();
            return count;
        }
    
    private:
        QList<T> list;
        QMutex mutex;
    };
    

    so my question is if this would actually be considered thread-safe and if this could be used without any problems across many threads? or is there a better solution?


  • Lifetime Qt Champion

    As long as you only use those three functions (which I doubt) it's fine although I would prefer a mutex outside the QList instead. And I would use a QMutexLocker instead manual lock/unlock.


Log in to reply