lundi 19 juillet 2021

execute a lambda function in different thread

Due to fixed requirements, I need to execute some code in a specific thread, and then return a result. The main-thread initiating that action should be blocked in the meantime.

void background_thread()
{
  while(1)
  {
    request.lock();
    g_lambda();
    response.unlock();
    request.unlock();
  }
}

void mainthread()
{
  ...
  g_lambda = []()...;
  request.unlock();
  response.lock();
  request.lock();
  ...
}

This should work. But it leaves us with a big problem: background thread needs to start with response mutex locked, and main-thread needs to start with request mutex locked...

How can we accomplish that? I cant think of a good way. And isnt that an anti-pattern anyways?

Aucun commentaire:

Enregistrer un commentaire