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;
});
}
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 [=]
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With