c++ - 创建线程时编译器错误

标签 c++ multithreading c++11 stl

<分区>

每次调用 ObjParser::loadData() 时,我都会尝试启动一个新线程,就像他们在 this 中所做的那样。示例。

所以我写了这段代码。

#include <thread>   
void ObjParser::loadData()
{
   thread loadingThread(_loadData);
   loadingThread.detach();
}

void ObjParser::_loadData()
{
   //some code
}

但是当我尝试编译它时,我得到了这个错误:

error C3867: 'ObjParser::_loadData': function call missing argument list; use '&ObjParser::_loadData' to create a pointer to member

所以我创建了一个指向成员函数的指针:

#include <thread>   
void ObjParser::loadData()
{
   thread loadingThread(&ObjParser::_loadData);
   loadingThread.detach();
}

void ObjParser::_loadData()
{
   //some code
}

但是编译器会提示:

error C2064: term does not evaluate to a function taking 0 arguments 

我不知道是什么导致了这个问题,你能给我一个解决这个问题的提示吗?

最佳答案

_loadData 似乎是一个非静态成员,因此您需要在一个对象上调用它 - 大概是调用 loadData 的同一个对象:

thread loadingThread(&ObjParser::_loadData, this);

或使用 lambda

thread loadingThread([this]{_loadData();});

或者,我可能会放弃额外的功能并只使用 lambda:

thread loadingThread([this]{  // or [] if you don't need to access class members
    // some code
});

关于c++ - 创建线程时编译器错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18596007/

相关文章:

c++ - 为什么我不能在 VS2008 的类中使用静态成员,例如静态结构?

.net - 当我从 .NET 生成一个新线程时到底发生了什么?

C 库从 BG 线程调用 kdb 函数

c++ - 使用 libc++ 正则表达式库 (C++11) 匹配 "beginning-of-line"

c++ - 编译器是否被迫拒绝无效的 constexpr?

c++ - 当事件发生时停止线程

c++ - C++ boost::shared_ptr 的深拷贝

c++ - 将 Matlab 转换为 C++

c# - WebClient 能够执行多个请求

c++ - 多线程程序比单线程程序慢