c++ - _beginthreadex 与成员函数

标签 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 也不能转换为静态成员变量,因为它使用私有(private)成员变量。

有什么想法吗?有没有更好的方法在这里开始讨论?

最佳答案

通常这是通过将“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();

关于c++ - _beginthreadex 与成员函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27176241/

相关文章:

c++ - 将左值引用存储到动态分配的数组

c++ - 二叉搜索树删除(Inorder Pred 方法)C++

c++ - CGAL 二维德劳内三角剖分 : How to get edges as vertex id pairs

c++ - 无法弄清楚为什么没有在 SDL 中绘制线

c++ - 将 int 转换为 Glib::ustring w/o stringstream

c++ - 将单个字符串分成多个堆栈

c++ - 如何让 gdb 从 icc "CHKP: Bounds check error"中断 `-check-pointers=write`

c++ - boost asio unix 套接字重用

C++ : how to get address of current function

c++ - 100选10,附加条件