编译器错误变量“未捕获";线程池的内部lambda函数 [英] Compiler Error variable "Not captured" inside lambda function for threadpool

查看:139
本文介绍了编译器错误变量“未捕获";线程池的内部lambda函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习c ++中的多线程,并试图建立线程池,但是遇到了一个编译器错误,提示错误:未捕获'mapperNodes'"和错误:未捕获'命令'".我已经读过一些有关使用"this"捕获lambda中的变量的信息,但到目前为止没有任何工作.

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.

如何在下面的代码的线程池lambda函数中使用command和mapperNoders变量?

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;
  });
}

推荐答案

编写pool.schedule([id]{ /*...*/ });时,您告诉编译器您的lambda只需要副本的值id变量,仅此而已.

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.

要将所有MapReduceServer::spawnMappers()变量(的副本)提供给lambda,可以将[id]更改为[=].

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

这篇关于编译器错误变量“未捕获";线程池的内部lambda函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆