C ++线程的成员函数 [英] C++ Thread in member function

查看:146
本文介绍了C ++线程的成员函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以在成员函数中使用线程来调用Windows中的C ++的成员函数吗?如果是,如何实现呢?下面是示例

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

感谢

推荐答案

这里实际上有多个问题:

There are actually multiple issues here:


  1. 你不能传递指向成员函数的指针作为 _beginthread()函数的例程。该函数需要一个指向全局或静态函数的指针。

  2. 标准C ++要求您完全限定成员函数名(即使在类中),并使用& ; 以获取指向成员的指针(编译器向您抱怨这一点)。

  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).

因为你不能传递一个成员函数指针到 _beginthread(),你需要创建一个包装全局或静态函数来使它工作。以下是一种实现方式:

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

当然,你需要以某种方式保证 MyClass object仍然存在,只要 fun_2()正在运行,或者不太好的事情会发生。如果您不必担心,请考虑使用 Boost.Thread 这基本上是和更多的你。

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.

这篇关于C ++线程的成员函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆