_beginthreadex成员函数
_beginthreadex with member functions
我不确定我是否以正确的方式解决这个问题,但我正在使用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 也不能强制转换为静态成员变量,因为它使用私有成员变量。
有什么想法吗? 有没有更好的方法来在这里开始一个线程?
通常,这可以通过将"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++构造函数成员初始化:传递参数
- 创建 std::函数,它返回具有函数成员值的变量.分段错误
- 如何在C++通过公共函数访问私有函数成员?
- 解释了构造函数成员初始化列表
- 调用std::函数成员时内存损坏
- 是否可以为模板类的模板函数成员设置别名?
- 捕获 lambda 函数C++成员变量
- 构造函数成员初始值设定项跨成员列出,安全吗?
- 获取与在模板参数中传递的函数成员类型相同的类
- 如何从公共函数成员访问地图私有成员
- C 构造函数成员分配优化
- 使用命名空间进行函数成员定义
- 函数成员作为 CUDA 内核的参数
- 模板基类函数成员的别名
- 函数成员中用于void和继承的enable_if
- 头文件中是否定义了一个很长的Class函数成员
- 类内/构造函数成员初始化
- 使用指向部分专用函数成员的指针自动填充向量
- 指向函数成员的指针