- 多线程Thread类实现
1.C语言实现方式:通过建立多个全局线程回调函数实现
2.面向对象实现方式:通过多态特性实现,虚函数在派生类中不同的行为方式
3.基于对象实现方式:通过boost::function和bind实现 - - 对于Linux线程创建方式:
int pthread_create(pthread_t *restrict thread,
const pthread_attr_t *restrict attr,
void *(*start_routine)(void*), void *restrict arg);
参数1.线程ID
参数2.线程属性
参数3.线程回调函数
参数4.回调函数
C语言实现线程方式:
通过建立全局线程回调函数实现,对于多个线程多个 不同任务需要建立多个全局函数,例子
void threadFunction1(void* arg)
{
printf("child thread 1\n");
pthread_exit(NULL);
}
void threadFunction2(void* arg)
{
printf("child thread 2\n");
pthread_exit(NULL);
}
int main(){
pthread_t thread1;
pthread_t thread2;
pthread_create(&thread1,NULL,threadFunction1,NULL);
pthread_create(&thread2,NULL,threadFunction2,NULL);
pthread_join(thread1,NULL);
pthread_join(thread2,NULL);
return 0;
}
面向对象封装方式
虚函数在派生类中不同的行为方式
class Thread
{
public:
Thread(){}
virtual ~Thread(){}
void start()
{
pthread_create(&_thread,NULL,thread_rountine,this);
}
void join()
{
pthread_join(_thread,NULL);
}
private:
static void* thread_rountine(void* arg)
{
// 不同的线程调用同样的thread_rountine函数,this指针指向不同的线程派生类,执行派生类中的run行为
Thread* thread = static_cast<Thread*>(arg);
thread->run();
return NULL;
}
virtual run()=0;
pthread_t _thread;
};
在prthread_create中为什么不能传递类的成员函数,使用静态的成员函数,因为pthread_create的参数三是一个普通的函数,而类的成员函数隐含传递一个this指针。
3. 基于对象封装方式(muduo库实现方式 boost::function/bind)
通过boost::function和bind实现
class Thread
{
public:
typedef boost::function<void ()> ThreadFunc;
explicit Thread(const ThreadFunc& func):_func(func){}
~Thread(){}
void start(){pthread_create(&_thread,NULL,thread_rountine,this);}
void join(){pthread_join(_thread,NULL);}
private:
ThreadFunc _func;
pthread_t _thread;
void run()
{
_func();
}
static void* thread_rountine(void* arg)
{
// boost::function类似于一种函数指针的声明,boost::bind类似于绑定一个函数
// 对于不同线程执行不同的行为时,只需要通过boost::bind改变即可实现。
Thread* thread = static_cast<Thread*>(arg);
thread->run();
return NULL;
}
};
class Foo
{
public:
void MemberFun()
{
cout<<"child thread1"<<endl;
}
void MemberFun1(int count)
{
cout<<"child thread2:"<<count<<endl;
}
};
int main()
{
Foo foo1();
Foo foo2();
Thread t(boost::bind(&Foo::MemberFun, &foo));
Thread t1(boost::bind(&Foo::MemberFun1,&foo2,3));
}
两种方式比较
个人观点:
继承实现的方式耦合性强,当功能扩展时,都需要建立新的派生类实现run方法
对于基于对象方式来说,耦合性低,对于功能扩展只需要编写一个函数就可以了,扩展性强