Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compiler Error variable "Not captured" inside lambda function for threadpool

I'm learning about multithreading in c++ and am trying to set up a thread pool, but am getting a complier error saying "error: ‘mapperNodes’ is not captured" and "error: ‘command’ is not captured". I've read a bit about using "this" to capture the variables in the lambda, but so far nothing has been working.

How can I use the command and mapperNoders variables in the thread pool lambda function in the code below?

void MapReduceServer::spawnMappers() throw() {
  vector<string> mapperNodes(nodes);
  random_shuffle(mapperNodes.begin(), mapperNodes.end());
  string command = buildCommand(mapperNodes[0], executablePath, mapperExecutable, mapOutputPath);

  ThreadPool pool(numMappers);//numMappers = 8

  for (size_t id = 0; id < numMappers; id++) {
    pool.schedule([id] {
      cout << oslock << "Thread (ID: " << id << ") has started." << endl << osunlock;

      spawnWorker(mapperNodes[0], command); /*compiler error here*/

      cout << oslock << "Thread (ID: " << id << ") has finished." << endl << osunlock;
  });
}
like image 217
user3316012 Avatar asked Dec 05 '15 05:12

user3316012


1 Answers

When you wrote pool.schedule([id]{ /*...*/ });, you told the compiler that your lambda only wants a copy of the value of the id variable, and nothing else.

To make (a copy of) all variables of MapReduceServer::spawnMappers() available to the lambda, you can change [id] for [=].

like image 68
Paulo1205 Avatar answered Nov 11 '22 05:11

Paulo1205