怎样把pthread_create的线程函数当作类的成员函数编译通过?
在SOLARIS C++4。2下在一个类的成员里调用了一个线程,
int baseClass::start()
{
................
thr_id = pthread_create(&thread_id, NULL, thread_method, NULL);
........................
}
但必须把thread_method声明如下:
void *thread_method(void *arg)
如果声明为void * baseClass::thread_method(void *arg)
就编译不过,我想把它作为成员函数,怎么办???不然破坏封装性 ,我还有子类需要
继承呢.
问题点数:20、回复次数:8Top
1 楼ecc(昏睡百年)回复于 2003-11-04 18:10:37 得分 0
不是很清楚 好像要 static void *.....Top
2 楼plainsong(短歌)()回复于 2003-11-04 18:22:09 得分 0
class baseClass
{
virtual void execute() = 0;
static void * thread_method(void * arg);
...
};
static void * thread_method(void * arg)
{
((baseClass*)arg)->execute();
...
}
int baseClass::start()
{
................
thr_id = pthread_create(&thread_id, NULL, thread_method, this);
........................
}
Top
3 楼libad()回复于 2003-11-06 14:25:55 得分 0
失败了,提示头文件出错
Error: Multiple declaration for static baseClass::thread_method(void*)
Top
4 楼libad()回复于 2003-11-06 14:43:41 得分 0
上面哪个错误是笔误,改正了后,有报:
ild: (undefined symbol) static baseClass::thread_method(void*) -- referenced in the text segment of ../bin/baseClass.o
Top
5 楼plainsong(短歌)()回复于 2003-11-06 17:51:31 得分 20
把作用域声明给漏了:
static void * baseClass::thread_method(void * arg)
{
((baseClass*)arg)->execute();
...
}
它是baseClass的静态成员,而不是全局函数。Top
6 楼xkak2(矗立云端)回复于 2003-11-06 18:00:01 得分 0
类的成员函数都有隐含的this指针,但是static成员函数没有,所以只需要用static成员函数就可以了。
另外,如果不想破坏封装,用namespace也是一个不错的选择。Top
7 楼libad()回复于 2003-11-07 09:12:01 得分 0
改为static void * baseClass::thread_method(void * arg)
{
((baseClass*)arg)->execute();
...
}
后报错:
Error: "static" is not allowed here.Top
8 楼plainsong(短歌)()回复于 2003-11-07 14:53:06 得分 0
void * baseClass::thread_method(void * arg)
{
((baseClass*)arg)->execute();
...
}
最近状态不好,总犯这种错误。Top




