Search code examples
c++multithreadingtbb

How to use TBB to run a function in a single thread


I'm trying to use TBB to use just one thread to run this piece of code but I do not know how to proceed.

I have read that I should use tbb::task_group but I do not know how to use it.

void CScene::load(const std::string &_name) {
  if (!references++) {
   setName(_name);
   Resources.setCurrentScene(my_name);

   TEntityParseContext ctx;
   ctx.name = my_name;
   parseScene("data/scenes/" + my_name + ".scene", ctx);

   dynamic = ctx.dynamic_scene;
   for (CHandle e : ctx.entities_loaded) {
     entities.push_back(e);
   }

   Engine.getScriptingModule().raiseEvent(CModuleScripting::SCENE_LOADED, 
   my_name);

   Resources.setCurrentScene("system");
  }
}

By the way, entities is a std::vector<CHandle> which is a private variable of the class


Solution

  • You just have to pass a lambda to the task_group::run function:

    CScene cs;
    tbb::task_group g;
    
    g.run([&cs]{cs.load("Name");});
    
    // maybe do some other work here
    
    // This function either waits or executes the lambda 
    // if no other thread is executing it
    g.wait();