关于C++中posix pthread线程函数在类中封装的问题

来源:互联网 发布:windows phone系统 编辑:程序博客网 时间:2024/05/30 23:15

    我们通常有这样的需求:需要在C++中用多线程处理可以并行处理的问题,且把线程函数封装在类中,而把线程函数封装在类中,导致了this指针作为默认的参数被传进了函数中,从而和线程函数参数不能匹配,不能通过编译。

市面上一般有以下几种解决方案:

1. 将线程函数作为全局函数, 从而避免了this指针作为隐含参数的作怪行为,但这样线程函数却无法访问类中的私有变量,此为一大缺憾。

解决方案: 是把所有的私有变量变为全局变量,这样极大程度上破坏了类的封装性。

2. 引入友元函数,从而可以访问私有变量,这种方法我没有试过,试过了再补充上来。

3. 将线程函数作为静态函数,因为在C++中静态函数没有this指针(即在内存中静态函数和普通全局函数几乎没有什么区别),故可以匹配编译通过, 但是当线程函数要访问私有变量呢?可以访问到吗?答案是不可以!

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

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

view plaincopy to clipboardprint?
  1. #include <iostream>  
  2. #include "pthread.h"  
  3. using namespace std;  
  4.   
  5. class A;  
  6. struct ARG  
  7. {  
  8.      A* pThis;  
  9.      string var;  
  10. };  
  11. class A  
  12. {  
  13.     public:  
  14.         A();  
  15.         ~A();  
  16.         static voidthread(void* args);  
  17.         void  excute();  
  18.     private:  
  19.         int iCount;  
  20.   
  21. };  
  22.   
  23. A::A()  
  24. {  
  25.     iCount = 10;  
  26. }  
  27. A::~A()  
  28. {  
  29.   
  30. }  
  31. void* A::thread(void* args)  
  32. {  
  33.      ARG *arg = (ARG*)args;  
  34.      A* pThis = arg->pThis;  
  35.      string var = arg->var;  
  36.      cout<<"传入进来的参数var: "<<var<<endl;  
  37.      cout<<"用static线程函数调用私有变量: "<<pThis->iCount<<endl;  
  38.   
  39. }  
  40.   
  41. void A::excute()  
  42. {  
  43.      int error;  
  44.      pthread_t thread_id;  
  45.      ARG *arg = new ARG();  
  46.      arg->pThis = this;  
  47.      arg->var = "abc";  
  48.      error = pthread_create(&thread_id, NULL, thread, (void*)arg);  
  49.      if (error == 0)  
  50.      {  
  51.          cout<<"线程创建成功"<<endl;  
  52.          pthread_join(thread_id, NULL);  
  53.      }  
  54. }  
  55. int main()  
  56. {  
  57.     A a;  
  58.     a.excute();  
  59.     return 0;  
  60. }  

上述代码在G++下编译通过, 本篇小总结基本涵盖了线程函数在类中封装的问题。

原创粉丝点击