Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Qt Development
  3. General and Desktop
  4. QList thread safety
Qt 6.11 is out! See what's new in the release blog

QList thread safety

Scheduled Pinned Locked Moved Solved General and Desktop
2 Posts 2 Posters 1.8k Views
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • K Offline
    K Offline
    Kayote
    wrote on last edited by
    #1

    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?

    1 Reply Last reply
    0
    • Christian EhrlicherC Offline
      Christian EhrlicherC Offline
      Christian Ehrlicher
      Lifetime Qt Champion
      wrote on last edited by
      #2

      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.

      Qt Online Installer direct download: https://download.qt.io/official_releases/online_installers/
      Visit the Qt Academy at https://academy.qt.io/catalog

      1 Reply Last reply
      4

      • Login

      • Login or register to search.
      • First post
        Last post
      0
      • Categories
      • Recent
      • Tags
      • Popular
      • Users
      • Groups
      • Search
      • Get Qt Extensions
      • Unsolved