tags:

views:

31

answers:

1

Here is the example code:

#include <iostream>
#include <list>
#include <tbb/task.h>
#include <tbb/task_group.h>
#include <stdlib.h>
#include <boost/thread.hpp>

using namespace tbb;

 long fib(long a)
{
  if (a < 2) return 1;

  return fib(a - 1) + fib(a - 2);
}

class PrintTask 
{
public:
    void operator()()
    {
        std::cout << "hi world!: " <<  boost::this_thread::get_id() << std::endl;

        fib(50);
    }
};

int main(int argc, char** argv)
{     
    task_group group;

    for (int i = 0; i < 100; ++i)
    {
      group.run(PrintTask());
    }      

    group.wait();

    return(0);
}

Here I'm computing a big fibonacci sequence just to simulate non-blocking computation. I was specting that this code would generate more than two threads (my computer is a Core2Duo), but only the first and second tasks are called. This is the spected?

A: 

Massively multithreading blocking behaviour (std::cout use) is an anti-pattern in multithreading and may result in bad behaviour, because it's the wrong thing to do. In addition, TBB reserves the right to implement group.run() however the hell it likes and spawn whatever threads it likes. If you only have a dual core, and you call with heavy work, why should it spawn more than two threads? The OS and other apps will happily eat remaining background time.

DeadMG
Sorry, the cout there is just for enumerate the thread id that is calling the task and so doesn't change the point I was making. If I understood what you said, paralellizing the application wouldn't improve the result? I known that in general the 100 tasks would take more time to be executed if made in parallel due to context switch and etcetera, but having to wait to 2 of them end to spawn another task doesn't make much sense to me.
scooterman
@scooterman: cout exhibits numerous threading behaviours, such as blocking. It's not thread safe to just use that way. You're impacting your threading performance substantially by using cout. In addition, there's nothing saying that TBB doesn't spawn two threads and put fifty tasks on each. Also, you really shouldn't mix TBB and boost::thread.
DeadMG