_beginthreadex与成员函数

时间:2014-11-27 17:32:58

标签: c++

我不确定我是否以正确的方式解决这个问题,但我正在使用C ++和Visual Studio 2013中的成员函数和线程。

其他答案我发现我必须将我的成员函数转换为静态函数,这允许我创建该线程。我遇到的问题是我不能调用任何其他也不是静态的成员函数。

这是我的代码的摘录:

//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;
}

非静态成员函数receiveMessageThread不能被转换为静态成员变量,因为它使用私有成员变量。

有什么想法吗?有没有更好的方法来开始一个线程?

1 个答案:

答案 0 :(得分:3)

通常这可以通过将“this”对象(即实例)作为参数传递给静态函数来解决:

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();