[Interest] how to run 21 threads concurrently

Sascha Cunz sascha-ml at babbelbox.org
Fri Oct 5 00:27:42 CEST 2012


Am Freitag, 5. Oktober 2012, 00:35:44 schrieb Sujan Dasmahapatra:
> which loop?
> for(int th=0; th<Threads.size(); th++)
> {
> if(Threads[th].isRunning())
> Threads[th].waitForFinished();
> Threads[th].cancel();
> }
> Threads.clear();
> 
> This loop is correct. If threads is running wait, then cancel it. braces
> are proper Sascha.

As Jan already pointed out in the other response, your code is equivalent to:

 for(int th=0; th<Threads.size(); th++)
 {
   if(Threads[th].isRunning())
   {
     Threads[th].waitForFinished();
   }
   Threads[th].cancel();
 }
 Threads.clear();

Which is not the same as you stated above. And will only work as desired, if 
you assume, that the QFuture objects are actually run in the order you 
scheduled them.

But, after all, the above code is a so called busy-loop. It will eat up 1 core 
almost completely (At least on most OS-configurations).

By the way, according to the documentation, a QFuture obtained via 
QtConcurrent::run() doesn't support cancel() at all.

A better alternative could be implemented using a Semaphore:

1. Just before the future finished, release one resource from the semaphore
2. After scheduling the futures accquire as many resources from the semaphore
   as you scheduled.

Like:

class Runner
{
public:
  void startFuturesAndWait()
  {
    for( int z = 0; z < 21; z++ )
    {
       QtConcurrent::run( &Runner::runMe, &mSemaphore, z );
    }
    mSemaphore.accquire( 21 ); // Blocks until all are done.
  }

private:
  static void runMe( QSemaphore* sem, int z )
  {
    Q_ASSERT( sem );
    yourFunction( z );
    sem->release( 1 );
  }
  
  QSemaphore mSemaphore;
};

Just typed this code to demonstrate the concept; did not even bother to 
compile or test it. But it should be used as simple as:

void test()
{
  Runner r;
  r.startFuturesAndWait();
  // We come back here, when all 21 futures are finished.
}




More information about the Interest mailing list