_beginthreadex with member functions

c++

Solution

Normally this is solved by passing "this" object (i.e. instance) as a parameter to the 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();

Problem

I'm not sure I'm going about this in the right way, but I'm working with member functions and threads in C++ and Visual Studio 2013. Other answers I've found said that I must cast my member function as a static function, which allows me to create that thread. The problem I have is that I cannot call any other member functions that also aren't 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 receiveMessageThread can't be cast as a static member variable either since it uses private member variables. Any ideas? Is there a better way to begin a thread here?

Original source