c++中的线程成员函数

C++ Thread in member function

本文关键字:成员 函数 线程 c++      更新时间:2023-10-16

我可以在成员函数中使用线程来调用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");
}

谢谢

这里实际上有多个问题:

  1. 不能将指向成员函数的指针作为例程传递给_beginthread()函数。该函数需要一个指向全局函数或静态函数的指针。
  2. 标准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,而不是自己滚动。