c++中的线程成员函数
C++ Thread in member function
我可以在成员函数中使用线程来调用windows中的c++成员函数吗?如果是,如何实现?示例
void Class::fun_1(void){
_beginthread(fun_2, 0, NULL); //This is the error line :: function call missing argument list; use '&Class::fun_2' to create a pointer to member
}
void Class::fun_2(void){
printf("hello");
}
谢谢
这里实际上有多个问题:
- 不能将指向成员函数的指针作为例程传递给
_beginthread()
函数。该函数需要一个指向全局函数或静态函数的指针。 - 标准c++要求完全限定成员函数名(即使在类中),并使用
&
来获取成员的指针(编译器向你抱怨这一点)。
因为你不能传递一个成员函数指针给_beginthread()
,你需要创建一个包装器全局或静态函数使其工作。下面是实现这一目标的一种方法:
class MyClass
{
public:
void fun_1()
{
_beginthread(&MyClass::fun_2_wrapper, 0, static_cast<void*>(this));
}
private:
void fun_2()
{
printf("hello");
}
static void __cdecl fun_2_wrapper(void* o)
{
static_cast<MyClass*>(o)->fun_2();
}
};
当然,您需要以某种方式保证只要fun_2()
在运行,MyClass
对象就仍然存在,否则就会发生不太好的事情。如果您不想为此担心,可以考虑使用Boost。线程,它基本上为你做这个和更多。
通常的方法是使用静态成员函数,该成员函数使用指向原始对象的void指针调用成员函数。
class Class
{
public:
void fun_1(void)
{
_beginthread( &Class::static_fun_2, 0, this );
}
void fun_2(void)
{
printf("hello");
}
private:
static void static_fun_2( void * args )
{
static_cast<Class*>(args)->fun_2();
}
};
然而,如果你开始需要向这些函数传递参数,事情就会变得有点复杂。我会考虑使用boost::thread和boost::bind,而不是自己滚动。
相关文章:
- 对RValue对象调用的LValue ref限定成员函数
- 为什么使用 "this" 指针调用派生成员函数?
- 将公共但非静态的成员函数与ALGLIB集成
- 使用指向成员的指针将成员函数作为参数传递
- 将重载的成员函数传递给函数模板
- 我不小心调用了一个没有自己类对象的成员函数.但这是怎么回事呢
- 如何在C++中使用非静态成员函数作为回调函数
- C++错误C2600:无法定义编译器生成的特殊成员函数(必须首先在类中声明)
- 关联容器的下界复杂性:成员函数与非成员函数
- 在 C++ 中用派生类型重写成员函数
- 链表的泛型函数remove()与成员函数remove)
- 如何将lambda作为模板类的成员函数参数
- constexpr构造函数需要常量成员函数时出现问题
- 将自由函数绑定为类成员函数
- 区分非成员函数和头文件中的成员函数
- 如何从子成员函数修改父公共成员变量
- 保留对其他类的成员函数的引用
- 在运算符重载定义中使用成员函数(const错误)
- 内联如何影响模块接口中的成员函数
- 将成员函数指针作为参数传递给模板方法