Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

multithreading - 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...