How to create copy of objects?



  • I have various lists and objects that are going to be modified/used in multiple threads at the same time and thus I need to make them thread-safe. So do to this I was going to use QMutex to lock() and unlock() access, but the thing is I'd like to prevent locking in places with code that might take a longer time to execute. So I thought of creating copies of the objects that are being used in multiple threads, which I can then use without having to use lock() on all of the code.

    So it would look something like this:

    QList<MyClass> myList;
    MyClass2 myClass;
    
    void ModifyList()
    {
       QMutex.Lock();
       myList.append(MyClass());
    
       myClass.someField = 2;
       QMutex.Unlock();
    }
    
    void UseList()
    {
        QMutex.Lock();
        QList<MyClass> copy = myList.CreateCopy();
        MyClass2 copy2 = myClass.CreateCopy();
        QMutex.Unlock();
    
        // Do stuff here with the copies without modifying the original and 
        // allowing 'ModifyList' to continue running while copies are being used here
    }
    

    The problem is, I can't seem to figure out how I can create copies of these lists and objects without ending up modifying the orignal ones. I'm sure there's also some other way than looping through all lists and adding it to a new list etc.?



  • This wildly depends on MyClass and MyClass2's copy constructors.

    If, for the sake of example we assume they are int (or any other Q_PRIMITIVE_TYPE):

    void copmuteList(){
    mutex.lock();
    QList<int> copyList = myList;
    int copy2 = myClass;
    mutex.unlock();
    // do some intense calculations on copyList and copy2 
    mutex.lock();
    myList = copyList;
    myClass = copy2;
    mutex.unlock();
    }
    

    You can eaven use QReadWriteLock instead of QMutex to allow different threads to take a copy in parallel but then police the write back of the results


  • Qt Champions 2017

    Hi
    how do you plan to sync it back?
    if each thread has a copy, thread Y alters the data
    Then thread Y4 also alters data.

    How do you copy it back so the result is consistent?



  • @mrjj I should probably have mentioned this, but I don't need to sync it afterwards as I only use the existing data to do calculations and rendering to be shown to the user, which is why I thought this would be the best way to do it.

    Thanks for the help VRonin! I actually wasn't aware of copy-constructors, but I've looked more into it and I seem to have gotten it working now. Thanks again :)


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.