sup*_*lar 5 c++ multithreading class
正如标题所说.以下是我的代码框架.
class CLASS
{
public:
void A();
private:
DWORD WINAPI B(LPVOID);
};
void CLASS::A()
{
DWORD (WINAPI CLASS::*thread)(LPVOID) = &CLASS::B;
...
CreateThread(NULL, 0, thread, &arg, 0, NULL);
...
}
Run Code Online (Sandbox Code Playgroud)
函数B需要CLASS的成员变量.
但是当我编译它时,我有一个错误代码.
它"无法将参数3从'DWORD(__ stdcall CLASS ::*)(LPVOID)'转换为'LPTHREAD_START_ROUTINE'"或类似的东西.
我不知道英语环境是否相同.
有人可以帮忙吗?
ybu*_*ill 11
说真的,如果你的编译器还不支持std :: thread(或boost :: thread):
class CLASS
{
public:
void A();
private:
void B(your args go here);
};
void CLASS::A()
{
boost::thread(&CLASS::B, this, your args go here);
}
Run Code Online (Sandbox Code Playgroud)
Naw*_*waz 10
static如果它是成员函数,你必须将你的回调函数定义为函数!
从我之前的回答 :(稍加修改)
更好的方法是定义一个可重用的类,其中纯虚函数run()由派生的线程类实现.以下是它应该如何设计:
//runnable is reusable class. All thread classes must derive from it!
class runnable
{
public:
virtual ~runnable() {}
static DWORD WINAPI run_thread(LPVOID args)
{
runnable *prunnable = static_cast<runnable*>(args);
return prunnable->run();
}
protected:
virtual DWORD run() = 0; //derived class must implement this!
};
class Thread : public runnable //derived from runnable!
{
public:
void newthread()
{
CreateThread(NULL, 0, &runnable::run_thread, this, 0, NULL);
}
protected:
DWORD run() //implementing the virtual function!
{
/*.....your thread execution code.....*/
}
}
Run Code Online (Sandbox Code Playgroud)
你必须使该成员函数static。
这里的问题是每个非静态成员函数都有一个隐式this参数,这实际上是编译器试图告诉你的——你的 nin 静态成员函数的签名与你期望的不同。
另请参阅对密切相关问题的回答。