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

     

  • 相关阅读:
    [转载]Ubuntu下ssh服务的安装与登陆(ssh远程登陆)
    Linux定时器
    sleep 和 usleep的实现方法
    如何在MATLAB下把模糊推理系统转化为查询表(转载)
    FPGA学习心得汇总(手中写代码,心中有电路)
    3D三栅极晶体管(摘抄)
    模糊控制
    Quartus II 中参数化模块库(LPM)的使用
    Quartus II 与modelsim连接不上的问题
    接近开关,光耦
  • 原文地址:https://www.cnblogs.com/yanghh/p/12924858.html
Copyright © 2011-2022 走看看