使用一些C的库时,需要让类的成员函数对接C的回调函数指针。
以pthread为例,利用类里的一个静态函数作为pthread_create的参数,将类的this指针传给这个静态函数,然后就可以想干什么干什么了。
-
template <typename A, typename R>
-
class thr: public boost::noncopyable
-
{
-
private:
-
typedef A arg_t;
-
typedef R res_t;
-
typedef pthread_t tid_t;
-
typedef boost::function func_t;
-
thr(){}
-
tid_t _tid;
-
arg_t _arg;
-
res_t _res;
-
func_t _func;
-
-
static void* _thread_func(void* arg)
-
{
-
((thr*)arg)->func();
-
return NULL;
-
}
-
public:
-
explicit thr(func_t func, arg_t arg): _func(func), _arg(arg){}
-
~thr(){}
-
tid_t get_tid() {return _tid;}
-
arg_t get_arg() {return _arg;}
-
res_t get_result() {return _res;}
-
void set_arg(arg_t arg) {_arg = arg;}
-
void set_result(res_t res){_res = res;}
-
-
void func() {_res = _func(_arg);}
-
int run() {return pthread_create(&_tid, NULL, _thread_func, this);}
-
int join()
-
{
-
void* p;
-
return pthread_join(_tid, &p);
-
}
-
};
-
-
class test
-
{
-
public:
-
char* f(int i)
-
{
-
char* s = new char[10];
-
sprintf(s, "%d", i);
-
return s;
-
}
-
};
-
-
int main()
-
{
-
test te;
-
thr th(boost::bind(&test::f, te, _1), 123);
-
th.run();
-
th.join();
-
-
char* s = th.get_result();
-
cout << th.get_result() << endl;
-
delete[] s;
-
return 0;
-
}
上面为了方便用了boost::function。使得整个类和boost::thread功能有点重复。
如果不想用boost,可以想下面这样,用继承的方式。
class thr
{
protected:
pthread_t _tid;
static void* _thread_func(void* arg) {return ((thr*)arg)->_func();}
virtual void* _func() = 0;
thr(const thr& o){}
public:
thr(){}
~thr(){}
int start_thread()
{
int re = pthread_create(&_tid, NULL, _thread_func, this);
if(re != 0) return re;
}
int join_thread()
{
void* p;
if(pthread_join(_tid, &p) != 0) return -1;
cout << (*(int*)p) << endl;
return 0;
}
};
class test: public thr
{
private:
int _i;
void* _func()
{
cout << "thread begin" << endl;
return &_i;
}
public:
test(int i):_i(i){}
};
int main()
{
test te(10);
te.start_thread();
te.join_thread();
return 0;
}
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/26239116/viewspace-2123701/
,如需转载,请注明出处,否则将追究法律责任。