C++中编写线程基础类,使用线程函数的方法


把成员函数作为线程函数,this指针会作为默认的参数被传进函数中,从而和线程函数参数(void*)不能匹配,不能通过编译。怎么解决呢?网上有一个解决办法,引用过来,自己记着。

摘自:http://hi.chinaunix.net/?uid-11770217-action-viewspace-itemid-48886
将线程函数作为静态函数,因为在C++中静态函数没有this指针(即在内存中静态函数和普通全局函数几乎没有什么区别),故可以匹配编译通过, 但是当线程函数要访问私有变量呢?可以访问到吗?答案是不可以!

解决方案: 将this指针作为参数传递给静态函数,这样可以通过该this指针访问所有的私有变量, 但是我要是还需要向静态函数中传递我自己需要的参数呢?

答案是:将this指针和需要的参数作为一个结构体一起传给静态函数,请看下面代码:

#include <iostream>
#include "pthread.h"
using namespace std;

class A;
struct ARG
{
     A* pThis;
     string var;
};
class A
{
    public:
        A();
        ~A();
        static void* thread(void* args);
        void  excute();
    private:
        int iCount;

};

A::A()
{
    iCount = 10;
}
A::~A()
{

}
void* A::thread(void* args)
{
     ARG *arg = (ARG*)args;
     A* pThis = arg->pThis;
     string var = arg->var;
     cout<<"传入进来的参数var: "<<var<<endl;
     cout<<"用static线程函数调用私有变量: "<<pThis->iCount<<endl;

}

void A::excute()
{
     int error;
     pthread_t thread_id;
     ARG *arg = new ARG();
     arg->pThis = this;
     arg->var = "abc";
     error = pthread_create(&thread_id, NULL, thread, (void*)arg);
     if (error == 0)
     {
         cout<<"线程创建成功"<<endl;
         pthread_join(thread_id, NULL);
     }
}


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM