【发布时间】:2019-04-17 17:56:31
【问题描述】:
我很好奇我在这里做错了什么。我有以下功能:
indexer.h:
class DtIndexer {
public:
static void ThreadedIndex(string folderPath);
indexer.cpp
void DtIndexer::ThreadedIndex(string folderPath) {
cout << "\t-> Indexing Folder: " << folderPath << endl;
cout << "\t->> Done..." << endl;
}
以及我创建线程的调用:
void DtIndexer::UpdateIndex(DatabaseData &data, bool isCreate) {
vector<thread> threadList;
for (string &s: data.FilePaths) {
const char *folder = GetFolderPath(s, data.IncludeSubFolders);
cout << "\t-> Adding Folder to Thread: " << folder << endl;
threadList.emplace_back(thread(ThreadedIndex, folder));
}
for_each(threadList.begin(), threadList.end(), mem_fn(&thread::join));
}
我的输出是这样的:
-> 将文件夹添加到线程:/index_2185
-> 将文件夹添加到线程:/index_1065
-> 索引文件夹:/index_1065
->> 完成...
-> 索引文件夹:/index_1065
->> 完成...
现在,我很确定它必须处理该方法的静态,但如果我删除静态,我会得到:
错误:无效使用非静态成员函数'void DtIndexer::ThreadedIndex(std::__cxx11::string)’ threadList.emplace_back(thread(ThreadedIndex, folder));
另外,如果我删除 static 并将函数添加到线程中,如下所示:
threadList.emplace_back(thread(&DtIndexer::ThreadedIndex, folder));
我明白了:
这里需要 /usr/include/c++/6/functional:1286:7: 错误:静态 断言失败:指向成员的参数数量错误 static_assert(_Varargs::value
我对 C++ 还是很陌生,所以,任何建议都将不胜感激。
【问题讨论】:
-
GetFolderPath是做什么的? -
当非
static时,必须在DtIndexer实例上调用DtIndexer::ThreadedIndex以获得有效的this。该实例是您缺少的参数。如果您不需要this,最好留下static或使用free function。 -
您是否知道在这一行中
thread(ThreadedIndex, folder)被称为thread(&ThreadedIndex, const char*),其中第二个参数指的是局部变量,并且当for 循环的迭代结束时,字符串被销毁。因此,当执行线程体时,字符串folderPath是从悬空指针创建的。您应该按值而不是const char*将字符串传递给线程。 -
@rafix07 是的,谢谢。这就是问题所在。我还将查看添加的信息 user4581301。再次感谢大家。如果您想将此作为答案发布(针对我的具体问题),我会将其标记为已接受
-
您的问题缺少minimal reproducible example。
标签: c++ multithreading threadpool