我想在一个类中启动一个线程,这个线程将调用一个函数,该函数是同一个类的成员。以下是我想要构建的示例代码。
void CM::ExecuteIt()
{
// Some Calculations
if(/*Condition*/)
{
hThreadArray = CreateThread(
NULL, // default security attributes
0, // use default stack size
MyThreadFunction, // thread function name
(LPVOID)&nProcessImage, // argument to thread function
0, // use default creation flags
&dwThreadIdArray);
}
}
void CM::MyThreadFunction(LPVOID lpParam)
{
HANDLE hStdout;
PMYDATA pDataArray;
// Some calculations that needs to be done
}但是在构建它的过程中,我得到了以下错误:"Error 16 Error C3867:'CM::MyThreadFunction':函数调用缺少参数列表;使用'&CM::MyThreadFunction‘创建指向成员的指针“
我不确定我做错了什么。有人能帮我解决这个问题吗?
发布于 2014-08-02 20:22:55
不能将非静态成员传递给CreateThread。传递的函数必须是独立的非成员函数,或者是静态成员函数。通常的方法是这样的:
class MyClass {
void StartThread() {
CreateThread(..., ThreadProcTrampoline, this, ...);
}
static DWORD WINAPI ThreadProcTrampoline(LPVOID param) {
MyClass* self = static_cast<MyClass*>(param);
return self->RealThreadProc();
}
DWORD RealThreadProc();
};要传递给线程过程的任何数据都应存储为该类的数据成员。
或者,由于您已将问题标记为C++11,因此可以使用std::thread。它在你可以传递的内容上更加灵活。
https://stackoverflow.com/questions/25094225
复制相似问题