Start a Large Task in Parallel with the Main Program

Instead of having all threads execute portions of a problem, it is possible to start a task in parallel with the main application. We’ve seen a number of requests for how to do this. The trick is to use a nonexecuting dummy task as the parent on which to synchronize, as shown in Example 11-37. Something very close to this trick is already used in tbb/parallel_while.h and tbb/parallel_scan.h, shown earlier.

One of the beautiful things about this approach is that each half of the program is free to invoke as much parallelism as it desires. The task-based approach of Threading Building Blocks does the load balancing and manages the assignment of tasks to threads without causing oversubscription.

Example 11-37. Using a dummy task for synchronization

 1 // The technique is similar to one used in tbb/parallel_while.h 2 3 #include "tbb/task.h" 4 #include "tbb/task_scheduler_init.h" 5 #include <stdio.h> 6 #include <stdlib.h> 7 8 //! Some busywork 9 void TwiddleThumbs( const char * message, int n ) { 10 for( int i=0; i<n; ++i ) { 11 printf(" %s: i=%d\n",message,i); 12 static volatile int x; 13 for( int j=0; j<20000000; ++j ) 14 ++x; 15 } 16 } 17 18 //! SideShow task 19 class SideShow: public tbb::task { 20 tbb::task* execute( ){ 21 TwiddleThumbs("Sideshow task",4); 22 return NULL; 23 } 24 }; 25 26 //! Start up a SideShow task. 27 //! Return pointer to dummy task that acts as parent of the SideShow. 28 tbb::empty_task* StartSideShow( ) { 29 ...

Get Intel Threading Building Blocks now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.