在c ++中运行类成员函数的线程

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)

  • +1.是的,一定要使用std ::/boost :: thread.而且,你甚至不需要绑定:`boost :: thread t(&CLASS :: B,this,your args if any go here);`.就如此容易. (2认同)

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)

  • 这是一个有点过时和笨拙的设计,必须派生一个类并重写一个函数来运行一个线程.更好地使用boost :: thread或类似的机制,将仿函数作为线程函数接受,并且不需要派生任何东西. (2认同)

sha*_*oth 3

你必须使该成员函数static

这里的问题是每个非静态成员函数都有一个隐式this参数,这实际上是编译器试图告诉你的——你的 nin 静态成员函数的签名与你期望的不同。

另请参阅对密切相关问题的回答

  • 在OP开始获得任何聪明的想法之前 - 非静态类成员函数指针是*奇怪的*。不仅调用约定与简单的“func(classname *this, ...)”不同,_指针表示_也很奇怪 - 在某些情况下,类成员函数指针最终可能是普通函数指针大小的 2 倍,因此甚至不要考虑强迫演员:) (3认同)