run threads of class member function in c++

后端 未结 3 1947
别那么骄傲
别那么骄傲 2020-12-06 08:26

As the title says. The following is my code skeleton.

class CLASS
{
public:
    void A();
private:
    DWORD WINAPI B(LPVOID);
};

void CLASS::A()
{
    DWOR         


        
相关标签:
3条回答
  • 2020-12-06 08:28

    You have to make that member function static.

    The problem here is that every non-static member function has an implicit this parameter and that's in fact what the compiler is trying to tell you - your nin-static member function has signature different from the one you expected.

    Also see this answer to a closely related question.

    0 讨论(0)
  • 2020-12-06 08:32

    You've to define your callback function as static function if it's member function!


    Better design : define a reusable class!

    From my previous answer: (with little modification)

    Even better would be to define a reusable class with pure virtual function run() to be implemented by the derived thread classes. Here is how it should be designed:

    //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.....*/
        }
    }
    
    0 讨论(0)
  • 2020-12-06 08:40

    Seriously, use std::thread (or boost::thread if your compiler doesn't support it yet):

    class CLASS
    {
    public:
        void A();
    private:
        void B(your args go here);
    };
    
    void CLASS::A()
    {
        boost::thread(&CLASS::B, this, your args go here);
    }
    
    0 讨论(0)
提交回复
热议问题