简体   繁体   中英

C++ Thread in member function

can I use thread in member function to call a member function for C++ in windows? 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. 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).

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. 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. If you much rather not have to worry about it, consider using Boost.Thread which does basically this and much more for you.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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