C ++ Topic in member function

Can I use thread in a member function to call a C ++ member function on Windows? If so, how to implement it? Here's an example

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

      

thank

+1


source to share


2 answers


There are several problems here:

  • You cannot pass a pointer to a member function as a function subroutine _beginthread()

    . The function requires a pointer to a global or static function.
  • Standard C ++ requires you to fully qualify a member function name (even within a class) and use it &

    to get a pointer to an element (the compiler complained to you about this point).

Since you cannot pass a member function pointer to _beginthread()

, you need to create a global or static wrapper function to make it work. Here's one way to do it:



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 object MyClass

will exist as long as it is executed fun_2()

, or not so well. If you don't have to worry about it, consider using Boost.Thread , which basically does this and more for you.

+7


source


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 using arguments for these functions, things get a little more complicated. I would look at using boost :: thread and boost :: bind instead of rolling around on my own.

+5


source







All Articles