您的位置:首页 > 编程语言 > C语言/C++

为什么在C++使用pthread_cre…

2017-06-29 10:13 302 查看
原文地址:为什么在C++使用pthread_create()的时候,类成员函数做线程的处理函数必须要定义成static类型的?作者:蓝月      
今天在进行多线程编程的时候遇到了一个编译问题:error: argument of type ‘void
(PIAMW::Communicator::)()’ does not match ‘void* (*)(void*)’

后来发现将线程处理函数声明为static类型,问题得解。

      
其实这个原因很简单,当把线程函数封装在类中,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);

    
}

}

int main()

{

    A a;

   
a.excute();

    return
0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: