简体   繁体   English

成员函数中的C ++线程

[英]C++ Thread in member function

can I use thread in member function to call a member function for C++ in windows? 如何在成员函数中使用线程在Windows中为C ++调用成员函数? If yes, how to implement it? 如果是,该如何实施? Here is the sample 这是样本

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");
}

Thanks 谢谢

There are actually multiple issues here: 这里实际上存在多个问题:

  1. You can't pass a pointer to a member function as the routine to the _beginthread() function. 您不能将指向成员函数的指针作为_beginthread()函数的例程传递。 The function requires a pointer to a global or static function. 该函数需要一个指向全局或静态函数的指针。
  2. Standard C++ requires that you fully qualify the member function name (even within the class) and use an & to obtain a pointer to the member (the compiler was complaining to you about this point). 标准C ++要求您完全限定成员函数名称(即使在类内),并使用&获取指向该成员的指针(编译器在此向您抱怨)。

Because you can't pass a member function pointer to _beginthread() , you need to create a wrapper global or static function to make it work. 因为您不能将成员函数指针传递给_beginthread() ,所以需要创建一个包装器全局或静态函数以使其起作用。 Here's one way to make that happen: 这是实现这一目标的一种方法:

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();
    }
};

Of course, you need to somehow guarantee that the MyClass object will still exist for as long as fun_2() is running, or not-so-good things will happen. 当然,您需要以某种方式保证只要fun_2()正在运行, MyClass对象仍将存在,否则会发生不好的事情。 If you much rather not have to worry about it, consider using Boost.Thread which does basically this and much more for you. 如果您不必担心,可以考虑使用Boost.Thread ,它基本上可以完成此任务,并且为您提供更多帮助。

The usual way to do this is to use a static member function that calls the member function using a void pointer to the original object. 通常的方法是使用静态成员函数,该成员函数使用指向原始对象的空指针来调用该成员函数。

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();
   }

};

However if you start needing to pass arguments to those functions things get a little more complicated. 但是,如果您开始需要将参数传递给这些函数,则事情会变得有些复杂。 I'd look at using boost::thread and boost::bind instead of rolling your own. 我会看看使用boost :: thread和boost :: bind而不是自己动手。

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

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