• 类成员函数如何作为pthread_create的线程函数?


    1. C++成员函数隐藏的this指针

       C++中类的普通成员函数都隐式包含一个指向当前对象的this指针,即:T *pThis,其中T为类类型。

       C++通过传递一个指向自身的指针给其成员函数从而实现程序函数可以访问C++的数据成员。这也可以理解为什么

       C++类的多个实例可以共享成员函数但是确有不同的数据成员。

    2. 类成员函数如何作为pthread_create的线程函数

       在C++的类中,普通成员函数作为pthread_create的线程函数就会出现参数问题,因为隐含的this指针的存在。

       具体解决方法有如下几种:

       a. 将函数作为为类内静态成员函数,即使用static修饰。将this指针作为参数传递,以使该方法可以访问类的非静态方法或者是变量。

    class MyClass
    {
    public:
        static void* ThreadFunc(void*);
        void Func()
        {
        }
    
        bool StartThread()
        {
            int ret = pthread_create(&_pthreadId, NULL, MyClass::ThreadFunc, this);
            if(ret != 0)
            {
                return false;
            }
            else
            {
                return true;
            }
        }
    private:
        pthread_t _pthreadId;
    };
    
    void* MyClass::ThreadFunc(void *arg)
    {
        MyClass *thiz = static_cast<MyClass *>(arg);
        thiz->Func();
        return NULL;
    };
    

       b. 对成员函数进行强制转换,当作线程的回调函数。具体代码如下:

    class MyClass
    {
        /* 定义Func类型是一个指向函数的指针,
           该函数参数为void*,返回值为void*
         */
        typedef void* (*pFUNC)(void *);
    
    public:
        void Func()
        {
        }
    
        bool StartThread()
        {
            pFUNC callback = reinterpret_cast<pFUNC>(&Func);
            int ret = pthread_create(&_pthreadId, NULL, callback, NULL);
            if(ret != 0)
            {
                return false;
            }
            else
            {
                return true;
            }
        }
    private:
        pthread_t _pthreadId;
    };
    

     

  • 相关阅读:
    XML常用操作
    关于C#的单斜杆和双斜杆
    XX驱动保护之KdDisableDebugger
    提供程序未返回 ProviderManifestToken 字符串 解决方案
    C# int转short
    C#_混淆/反混淆,逆向/反逆向之Dotfuscator
    mouseout和mouseover、mouseenter和mouseleave
    输入法下keypress、keyup失效的解决方案
    linux常用基本命令
    如何把已完成的项目部署到服务器
  • 原文地址:https://www.cnblogs.com/yanghh/p/12924858.html
Copyright © 2020-2023  润新知