Linux下使用C++创建线程,求助
请高手指点下:
代码如下:
- C/C++ code
#include <iostream>#include <pthread.h>#include <stdlib.h>using namespace std;/*新创建1个线程要执行的操作测试函数*/void f1(void*)//{ int i; for(i=0;i<6;++i) { sleep(2);//usleep(),us cout<<"Thread is running in f1..."<<i<<endl; }}/***定义的一个类,其中一个成员函数shout可以创建一个线程,每隔一段时间打印age,name变量。**/class Person{ private: float height; int age; string name; pthread_t pid; void* pshout(void*); public: Person(int n=19,string nm="zhang"):age(n),name(nm) { cout<<"A new person is born..."<<endl; } void shout(); pthread_t getPID();};/**类中线程函数实际操作**/void* Person::pshout(void*){ for(int i=age;i<100;++i) { cout<<name<<", age"<<age<<endl; sleep(1);//1s }//stopped when age is 100}/**类中创建线程的函数**/void Person::shout(){ pthread_t id=0; int res=0; res=pthread_create(&id,NULL,pshout,NULL); /**这一句一直报错,编译错误,说是pshout类型转换无效*/ if(res!=0) { cerr<<"Error!"<<endl; exit(1); } pid=id;}pthread_t Person::getPID(){ return pid;}int main(){ pthread_t id; int ret; ret= pthread_create(&id,NULL,(void*)f1,NULL); if(ret!=0) { cout<<"Creat pthread error!"<<endl; exit(1); } for(int i=0;i<6;++i) { sleep(1.5); cout<<"This is main() "<<i<<endl; } pthread_join(id,NULL); return 0;}
疑问:每次编译时都报shout中的线程创建函数中对pshout的调用类型转换无效!!但是对于函数f1的调用为什么没有问题呢?
编译工具:Ubuntu下使用codeblocks,gcc编译器。
[解决办法]
类中的线程函数应该写static
[解决办法]
C++中member function会有一个“隐藏”的参数
Person* this
你的线程函数实际上是void* Person::pshout(Person* this,void*)
所以不行,一般都是static member function为类中线程函数的
不过好像用什么bind functional 等可以实现非static 的
具体的我没研究过