5

I want to get a thread-pool behavior using TBB. But whenever I read documents about TBB they always talk about parallel-for, parallel-dowhile etc. In contrast what I need is a main thread to assign tasks to a thread pool so those tasks will be executed 'on their own' - execute tasks asynchronously. Tasks here can be event handling for a GUI.

Is the TBB task scheduler appropriate for such behavior? The impression I got from task scheduler is that it's only beneficial if I have tasks that can be broken down and executed in parallel to each other.

Alexey Kukanov
  • 12,479
  • 2
  • 36
  • 55
Dula
  • 1,404
  • 1
  • 14
  • 29
  • 2
    Download the "Design Patterns" guide from http://threadingbuildingblocks.org/documentation.php. It specifically mentions offloading long-running tasks from the GUI thread (see Chapter 8, "GUI Thread"), and has a simple example showing how it's done. – Jim Mischel Nov 28 '11 at 20:41

1 Answers1

10

Starting from version 3.0, TBB has support for asynchronous execution of tasks. For that, a special work offering method tbb::task::enqueue() was added. Unlike tbb::task::spawn(), this method guarantees that the enqueued task will be executed even if the originating thread never enters a task dispatch method such as wait_for_all().

A short usage example for task::enqueue():

class MyTask : public tbb::task {
    /*override*/ tbb::task* execute() {
        // Do the job
        return NULL; // or a pointer to a new task to be executed immediately
    }
};

MyTask* t = new (tbb::task::allocate_root()) MyTask();
tbb::task::enqueue(*t);
// Do other job; the task will be executed asynchronously

As @JimMishell mentioned in the comment, an example how to use it for handling of GUI events can be found in "Design Patterns"; and the formal description of the method is available in the Reference manual (see TBB documentation for both).

Cosmo Harrigan
  • 895
  • 1
  • 8
  • 22
Alexey Kukanov
  • 12,479
  • 2
  • 36
  • 55