zoukankan      html  css  js  c++  java
  • 类成员函数如何作为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;
    };
    

     

  • 相关阅读:
    react-native ios打包和Android打包
    用create-react-app创建的react项目怎么解决打包体积过大
    react native 新建项目运行报错
    微信分享等配置,微信授权失败讲解
    微信公众号的code,微信授权
    linux 递归删除指定文件
    mariaDB安装 无密码就可以登录、远程访问、及新版本初始化密码
    mysql 可重复插入、创建语句
    redis数据库入门
    Extjs 3.4 同值合并
  • 原文地址:https://www.cnblogs.com/yanghh/p/12924858.html
Copyright © 2011-2022 走看看