threadpool | Overview | Reference | Tutorial | Examples | Design

Tutorial | Quick Start | Prioritized Tasks | Arbitrary Task Functions | Advanced Pool Instantiation

Prioritized Tasks

TODO This tutorial is out dated.

It's easy to prioritize asynchronous tasks by using the task adaptor prio_task_func. The following source listing illustrates how to setup the pool and add the tasks:

    01
    02  #include "threadpool.hpp"
    03
    04  using namespace boost::threadpool;
    05
    06  // Some example tasks
    07  void normal_task()
    08  {
    09    ...
    10  }
    11
    13  void important_task()
    14  {
    15    ...
    16  }
    17
    18  void execute_prioritized()
    19  {
    20    // Create prioritized thread pool container without any threads.
    21    scoped_pool<prio_pool, 0> tp;
    22
    23    // Add some tasks to the pool.
    24    tp += prio_task_func(5,   &normal_task);
    25    tp += prio_task_func(100, &important_task);
    26    tp += prio_task_func(7,   &normal_task);
    27
    28    // Add the some threads to the pool. This will start the execution of the tasks.
    29    tp->resize(2);
    30
    31    // The tasks are processed according to their priority: important_task(100), nonrelevant_task(7), nonrelevant_task(5).
    32
    33    tp->wait();
    34
    35    // Now all tasks are finished and the pool will be destroyed safely when tp goes out of scope.
    36  }
    37

Like in the first tutorial we start including the main header file and defining some tasks.

At line 21 a prioritized thread pool is created. That means that the pool's tasks are arranged according to their priority before they get executed. Therefore the tasks themselves have to realize a partial ordering based on operator<.

The adaptor prio_thread_func satisfies our requirements regarding the order and is just a small wrapper object for the task functions. In line 24 to 26 some prioritized tasks are scheduled. This time the pool's schedule function is used and like smart pool's += operator this function returns immediately.

At line 29 the first thread is added to the pool and the execution of important_task begins. As we have only one thread the tasks are processed sequentially.

Finally wait() is called to ensure that all tasks are finished before our example function returns and the pool is destroyed. This is very important since the behavior is undefined if pool's lifetime ends while tasks are executed.

Copyright © 2005-2008 Philipp Henkel | Overview | Reference | Tutorial | Examples | Design