【发布时间】:2025-12-28 12:00:11
【问题描述】:
我有一个相当基本的问题,但不确定它的来源:并发环境中的 lambda 捕获评估或滥用文件系统库。
这是示例代码:
#include <iostream>
#include <vector>
#include <thread>
#include <boost/filesystem.hpp>
using namespace std;
using namespace boost::filesystem;
void query(const string filename)
{
cout << filename << " ";
}
int main() {
path p("./");
vector<thread> thrs;
for(auto file = directory_iterator(p); file != directory_iterator(); ++file)
{
thread th( [file] {query(file->path().string());} );
thrs.push_back(move(th));
}
for (auto& t : thrs)
t.join();
return 0;
}
在运行时给出:
:~/workspace/sandbox/Release$ l
main.o makefile objects.mk sandbox* sources.mk subdir.mk
:~/workspace/sandbox/Release$ LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/home/a/custom-libs/boost-1_59/lib/ ./sandbox
./subdir.mk ./sources.mk ./sandbox ./objects.mk ./main.o ./main.o
注意竞争条件 - 并非所有文件最终都被传递给线程函数(在此运行时 makefile 丢失)。
我可以通过在本地变量中提取参数来找到解决方法,将循环体重写为:
auto fn = file->path().string();
thread th( [fn] {query(fn);} );
thrs.push_back(move(th));
竞态条件从何而来?
file->path().string() 不是在创建线程的时候进行评估吗?
【问题讨论】:
-
所有线程同时使用 std::cout ...
标签: multithreading c++11 boost