日期:2014-05-16  浏览次数:20680 次

如何在类中建立线程
各位大虾,我遇到一个问题,我在类中不能建立线程,但是不用类的话又可以建立县城,不知道是为什么,我把代码贴出来,如下:
------------------不在类里面建立线程的代码-----------------
#include <phtread.h>
#include <iostream.h>
using namespace std
void *pp(void *){
  while(1){
  cout<<"I am pp thread"<<endl;
  sleep(2);
  }
}
int main(ing argc, char *argv[]){
  pthread_t pid;
  pthread_create(&pid,NULL,pp,NULL);
  while(1){
  cout<<"I am the main thread"<<endl;  
  }
}
这时可以编译通过,并且可以正常运行。但是我把它放到类里面,就不可以编译通过,我把代码帖出来,如下:
------------------------在类里面建立线程代码---------------------------
void Mythread(){
private:
  pthread_t pid;
public:
  Mythread(){}
  ~Mythread(){}  
  void *pp(void *){
  while(1){
  cout<<"I am pp thread"<<endl;
  }
  }
  void creat_pthread(){
  pthread_create(&pid,NULL,pp,NULL);
  }
}
int main(ing argc, char *argv[]){
  //pthread_t pid;
  while(1){
  cout<<"I am the main thread"<<endl;
  }
}
这时就会提示,pthread_create(&pid,NULL,pp,NULL)与原函数不匹配,如果把它改成pthread_create(&pid,NULL,NULL,NULL)就可以通过,问题好像是出在pthread_create函数的第三个参数上,在类里面程序找不到线程建立时的入口函数。
我的问题是:我该如何在类里面建立线成呢?
我用的是FC4系统


------解决方案--------------------
现在没g++环境,不好帮你调,你试试在void *pp(void *)前面加上static看看。

static void *pp(void *){}
------解决方案--------------------
g++ -lpthread
加上-lpthread
------解决方案--------------------
线程函数可以是类的静态成员函数
------解决方案--------------------
static void *pp(void *){ }
------解决方案--------------------
因为如果不是static的话,每个类的实例都有一个自己的void *pp,这时候pthread_create不知道该找哪个。

加了static以后,所有的类实例共享同一个void* pp,而且放在堆空间里,pthread_create就能找到了....
------解决方案--------------------
在类没有声明对象前这个类是不存在的,所以不可以使用非静态成员函数作为线程函数

所以,要么就用static,要么可以用全局函数,把函数定义放在类外。
------解决方案--------------------
线程过程函数不能是局部函数, 如果是类的成员函数要加static啊.
pthread_create(&pid,NULL,Mythread::pp,NULL);
------解决方案--------------------
线程的过程没有必要放在类的成员里面.

放在类外面, 把需要访问的类成员声明为public, 在外面就可以访问了.
因为一个对象的成员能被另一个线程访问已经不安全了, private已经没有意义.