17.3.  Exercises: QThread and QtConcurrent

[ fromfile: ex-threads.xml id: ex-threads ]

  1. Without using QtConcurrent, write a multithreaded Game of Life example, where LifeServer creates and manages LifeWorker threads (up to QThreadPool::maxThreadCount()) and distributes the calculations across those threads to get faster speed. Let the user set the number of threads from a QSpinBox.

    Use QMutex or QReadWriteLock to synchronize access to shared data. Use the PrimeThreads producer-consumer example from Example 17.15 as a guide, and reuse any code you want from the Life example in Section 17.2.3. Figure 17.7 shows a possible high-level design in UML.

    Figure 17.7.  Multithreaded Life UML

    Multithreaded Life UML

  2. Start with the application shown in Section 17.2.2 and add a progress bar to the GUI that works using either algorithm.

  3. In this exercise you revisit some of the image manipulation techniques that was introduced in Section 10.5.1 and apply them in parallel, across several threads, to produce random collages.

    Write an application that lets the user to select as many images as desired from the disk and then uses a QtConcurrent algorithm to distribute the labor of randomly applying image manipulation functions (with random arguments if appropriate) to random numbers of copies of the images.

    After the image manipulations have been completed, use a QtConcurrent algorithm to randomly scale down each of the manipulated images and paint them into random locations inside an initially blank image – the collage.

    After the collage has been produced and saved to disk, display it on the screen.

    Figure 17.8 was produced using 28 photos, each of which was copied from 1 to 5 times, manipulated, scaled, and inserted into a (default) 640x480 image. The size of the final collage can (optionally) be set with commandline arguments.

    Figure 17.8.  Collage example

    Collage example