当前位置: 技术问答>linux和unix
pthread_create错误,怎么在C++类中定义线程函数指针
来源: 互联网 发布时间:2016-06-22
本文导语: class Identity { public : Identity(); void *Shown(void * arg); void *RunExec(void * arg); private: int a; }; Identity:: Identity() { pthread_t pthread1,pthread2; pthread_create(&pthread1, NULL,Shown, NULL); pthread_create(&pthread2, NULL, RunExec, NULL)...
class Identity
{
public :
Identity();
void *Shown(void * arg);
void *RunExec(void * arg);
private:
int a;
};
Identity:: Identity()
{
pthread_t pthread1,pthread2;
pthread_create(&pthread1, NULL,Shown, NULL);
pthread_create(&pthread2, NULL, RunExec, NULL);
pthread_join(pthread1,NULL);
pthread_join(pthread2,NULL);
}
void * Identity::Shown(void * arg)//->这里应该怎么定义,是否正确
{
a=1;
printf("pthread1--->a=%dn",a);
}
void *Identity::RunExec(void * arg)//->这里应该怎么定义,是否正确
{
a=2;
printf("pthread2--->a=%dn",a);
pthread_exit(0);
}
int main(void)
{
Identity b;
return 0;
}
运行程序显示这两个子函数不匹配,以下是错误信息:
pthread.cpp:17: no matches converting function `Shown' to type `void*(*)(void*)
'
pthread.cpp:9: candidates are: void* Identity::Shown(void*)
pthread.cpp:18: no matches converting function `RunExec' to type `
void*(*)(void*)'
pthread.cpp:10: candidates are: void* Identity::RunExec(void*)
好像怎么改都不对,难道只能在C语音里产生线程吗?(即怎么利用C++类产生线程?)
{
public :
Identity();
void *Shown(void * arg);
void *RunExec(void * arg);
private:
int a;
};
Identity:: Identity()
{
pthread_t pthread1,pthread2;
pthread_create(&pthread1, NULL,Shown, NULL);
pthread_create(&pthread2, NULL, RunExec, NULL);
pthread_join(pthread1,NULL);
pthread_join(pthread2,NULL);
}
void * Identity::Shown(void * arg)//->这里应该怎么定义,是否正确
{
a=1;
printf("pthread1--->a=%dn",a);
}
void *Identity::RunExec(void * arg)//->这里应该怎么定义,是否正确
{
a=2;
printf("pthread2--->a=%dn",a);
pthread_exit(0);
}
int main(void)
{
Identity b;
return 0;
}
运行程序显示这两个子函数不匹配,以下是错误信息:
pthread.cpp:17: no matches converting function `Shown' to type `void*(*)(void*)
'
pthread.cpp:9: candidates are: void* Identity::Shown(void*)
pthread.cpp:18: no matches converting function `RunExec' to type `
void*(*)(void*)'
pthread.cpp:10: candidates are: void* Identity::RunExec(void*)
好像怎么改都不对,难道只能在C语音里产生线程吗?(即怎么利用C++类产生线程?)
|
这种情况下,推荐的方法是,把线程函数要用的变量都放在一个结构里,把结构指针作为参数传给线程函数。
也就是pthread_create的第4个参数。
|
需要用静态成员函数。
#include
using namespace std;
#include
void *Bar(void *arg)
{
cout