_beginthreadex with member functions

I'm not sure if I'm going to get it right, but I'm working with member functions and streams in C ++ and Visual Studio 2013.

The other answers I have found say that I have to use the member function as a static function that allows me to create this thread. The problem is that I cannot call any other member functions that are also not static.

Here's an excerpt of my code:

//Start the thread for the receive function
    receiveMessageHandle = (HANDLE)_beginthreadex(0, 0, &foo::receiveMessageThread, (void*)0, 0, 0);
    return 0;
}

unsigned int __stdcall foo::receiveMessageThread(void *threadToStart)
{
    foo::receiveMessages(); //Non-static member function!
    return 0;
}

      

The non-static member function getMessageThread cannot be selected as a static member variable or using private member variables.

Any ideas? Is there a better way to start a thread here?

+3


source to share


1 answer


This is usually solved by passing the "this" object (like an instance) as a parameter to a static function:



class foo
{
public:
    void startTheThread()
    {
        //Start the thread for the receive function (note "this")
        receiveMessageHandle = 
            _beginthreadex(0, 0, &foo::receiveMessageThread, this, 0, 0);
    }
private:
    void receiveMessages()
    {
    }

    static unsigned int __stdcall receiveMessageThread(void *p_this)
    {
        foo* p_foo = static_cast<foo*>(p_this);
        p_foo->receiveMessages(); // Non-static member function!
        return 0;
    }
    unsigned int receiveMessageHandle;
};

// somewhere
foo* the_foo = ...
the_foo->startTheThread();

      

+3


source







All Articles