如何在同一类(C ++,MFC)中调用工作线程? [英] How do i call worker thread in a same class (C++, MFC)?
问题描述
这是我的代码,其中包含错误:
Here is my code which contains error:
void ClassA::init()
{
HANDLE hThread;
data thread; // "thread" is an object of struct data
hThread = CreateThread(NULL, 0, C1::threadfn, &thread, 0, NULL);
}
DWORD WINAPI ClassA::threadfn(LPVOID lpParam)
{
data *lpData = (data*)lpParam;
}
错误:
error C3867: 'ClassA::threadfn': function call missing argument list; use '&ClassA::threadfn' to create a pointer to member
使工作线程在单个类中工作的正确方法是什么?
What is the proper way to make the worker thread working in a single class?
推荐答案
线程创建函数不了解C ++类;它只支持C ++类.这样,您的线程入口点必须是静态类成员函数或非成员函数.您可以将this
指针作为lpvThreadParam
参数传递给CreateThread()
函数,然后让静态或非成员入口点函数仅通过该指针调用threadfn()
函数.
The thread creation functions are not aware of C++ classes; as such, your thread entry point must be either a static class member function, or a non-member function. You can pass in the this
pointer as the lpvThreadParam
parameter to the CreateThread()
function, then have the static or non-member entry point function simply call the threadfn()
function via that pointer.
如果threadfn()
函数 是静态的,请确保将&
放在C1::threadfn
之前.
If the threadfn()
function is static, then make sure you put &
before C1::threadfn
.
这是一个简单的例子:
class MyClass {
private:
static DWORD WINAPI trampoline(LPVOID pSelf);
DWORD threadBody();
public:
HANDLE startThread();
}
DWORD WINAPI MyClass::trampoline(LPVOID pSelf) {
return ((MyClass)pSelf)->threadBody();
}
DWORD MyClass::threadBody() {
// Do the actual work here
}
HANDLE MyClass::startThread() {
return CreateThread(NULL, 0, &MyClass::trampoline, (LPVOID)this, 0, NULL);
}
这篇关于如何在同一类(C ++,MFC)中调用工作线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!