Linux下使用C++创建线程,求助
本帖最后由 hello_world_2012 于 2012-08-04 20:57:34 编辑
请高手指点下:
代码如下:
#include
#include
#include
using namespace std;
/*新创建1个线程要执行的操作
测试函数*/
void f1(void*)//
{
int i;
for(i=0;i<6;++i)
{
sleep(2);//usleep(),us
cout<
}
}
/***
定义的一个类,其中一个成员函数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<
}
void shout();
pthread_t getPID();
};
/**类中线程函数实际操作**/
void* Person::pshout(void*)
{
for(int i=age;i<100;++i)
{
cout<
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<
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<
exit(1);
}
for(int i=0;i<6;++i)
{
sleep(1.5);
cout<
}
pthread_join(id,NULL);
return 0;
}
疑问:每次编译时都报shout中的线程创建函数中对pshout的调用类型转换无效!!但是对于函数f1的调用为什么没有问题呢?
编译工具:Ubuntu下使用codeblocks,gcc编译器。
------解决方案--------------------
类中的线程函数应该写static
------解决方案--------------------
C++中member function会有一个“隐藏”的参数
Person* this