在C++中使用pthread
作者:Leven 日期:2008-04-26 22:24:01
pthread便是大名鼎鼎的posix多线程库了.然而pthread的多线程基于C回调函数,在C++中应用是个不大方便的问题.由于c++的类成员函数指针是无法直接在pthread中回调的,因此,如果我们想要在C++中使用pthread多线程,必须要借助其他的技巧才可以做到.
首先,我们要兼容pthread的静态函数式回调,同时又要动态调用成员函数,因此,要有一个类负责转发调用,再次,我们考虑如何调用类,为了方便,我们用C++仿函数在线程内调用成员函数.
所以,首先我们想到实现一个ThreadCall类:
C++代码
- class ThreadCall{
- public:
- static void *Fun(void *data){
- //这儿如何定义呢?
- }
- };
我们这儿只能传入一个void*的数据,但是我们需要知道的数据呢?应该包括要调用的类,以及要传入的参数.同时,对这个类,我们还要求拥有仿函数接口,因此,我们做如下定义:
C++代码
- //首先定义一个ThreadClass接口,所有回调类都直接或者间接继承自该类
- //它规定了回调接口
- class ThreadClass{
- public:
- virtual void *operator()(void *)=0;
- };
C++代码
- //再定义一个线程信息结构,其中包含了要调用的class和出入的数据
- struct _threadInfo{
- ThreadClass *threadClass;
- void *data;
- };
- typedef _threadInfo ThreadInfo;
OK,再次回到我们的ThreadCall类,现在我们就可方便的写出它的实现了:
C++代码
- class ThreadCall{
- public:
- static void *Fun(void *data){
- ThreadInfo *info=(ThreadInfo *)data;
- return info->threadClass->operator ()(info->data);
- }
- };
这样,我们就实现了C++式的使用pthread,虽然麻烦了点,但是实现了类成员函数线程调用,还是值得的.现在我们来测试下:
C++代码
- class MyThreadClass : ThreadClass{
- public:
- virtual void *operator()(void *data){
- char *str=(char *)data;
- cout<<str<<endl;
- return NULL;
- };
- };
- int main(int argc,char *argv[]){
- MyThreadClass threadClass;
- ThreadInfo info;
- info.threadClass=(ThreadClass *)&threadClass;
- info.data="hello";
- pthread_t pid;
- pthread_create(&pid,NULL,&ThreadCall::Fun,&info);
- system("pause");
- }
执行程序,子线程成功打印出"hello"的信息.
评论: 0 |
引用: 0 |
查看次数: 681
发表评论
上一篇
下一篇
文章来自:
Tags: