为什么在C++使用pthread_create()…

来源:互联网 发布:网络主播灯光摆放图 编辑:程序博客网 时间:2024/06/06 04:47
      今天在进行多线程编程的时候遇到了一个编译问题: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();
    return0;
}




0 0
原创粉丝点击