【发布时间】:2015-12-05 05:01:00
【问题描述】:
我正在学习 C++ 中的多线程,并试图建立一个线程池,但我收到一个编译器错误,提示“错误:'mapperNodes' 未被捕获”和“错误:'command' 未被捕获”。我已经阅读了一些关于使用“this”来捕获 lambda 中的变量的信息,但到目前为止还没有任何效果。
如何在下面的代码中使用线程池lambda函数中的command和mapperNoders变量?
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;
});
}
【问题讨论】:
-
@MM,我认为你错了。 TC++PL 第 4 版第 11.4.4 节。明确表示可以省略空参数列表。例如,this article in cppreference.com 也是如此。
-
@Paulo1205 很酷,很高兴知道
标签: c++ multithreading lambda scope