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

Safe to pass const references from one thread to another with QtConcurrent::run()?



  • If I use QtConcurrent::run() to process some number crunching on another thread, is it okay to use a function for run() that accepts const references to objects? Will references be in tact across threads? This would be read-only reference; I am thinking it could avoid copying a lot of data for the number crunching over into a pass-by-value function. The function would not mutate any existing objects, just return a QVector of results based on the data it was passed.

    The docs mention that run() will make a copy of data, so perhaps this would also apply to a reference, in which case I wonder if a pointer would be any better?


  • Moderators

    As you've already read from the docs, the arguments will be copied. Even if you pass a const reference, Qt will make a copy from your const reference.

    However, what type is your object? If it is an "implicitly shared":http://qt-project.org/doc/qt-5/implicit-sharing.html object (like a QVector), the copying is cheap so you don't have to worry. Otherwise, you will need to pass a pointer, to avoid copying large datasets.

    Also, will your object(s) be modified by any other threads while you do your number-crunching? If so, remember to use a QReadWriteLock for both reading and writing.



  • I will not be modifying any objects in my threaded calculations, just using threads to create new data from heavy calculations.

    Would it better to pass a pointer (for read-only purposes) or to encapsulate what is needed in a QVector, etc, when cheaply sending data to another thread?


  • Moderators

    [quote author="qttester5" date="1397442407"]Would it better to pass a pointer (for read-only purposes) or to encapsulate what is needed in a QVector, etc, when cheaply sending data to another thread?[/quote]It depends on your existing design. What does your data structure currently look like?



  • It is basically an object with several member variables, some of which are QVectors of other custom types.


  • Moderators

    [quote author="qttester5" date="1397445217"]It is basically an object with several member variables, some of which are QVectors of other custom types.[/quote]Passing a pointer makes the most sense.

    Packing an object into an implicitly shared container involves copying the object, so you won't save anything there.


Log in to reply