繁体   English   中英

成员函数中的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");
}

谢谢

这里实际上存在多个问题:

  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.Thread ,它基本上可以完成此任务,并且为您提供更多帮助。

通常的方法是使用静态成员函数,该成员函数使用指向原始对象的空指针来调用该成员函数。

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而不是自己动手。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM