Thread.h
#ifndef _thread_h_#define _thread_h_#include <pthread.h> #include <boost/function.hpp>class thread{ Public:typedef boost::function<void () > Threadfunc;explicit Thread (const threadfunc& func); void Start (); void Join (), void Setautodelete (bool autodelete);p rivate:static void* threadroutine (void* arg), void Run (); ThreadFunc func_;pthread_t threadid_;bool Autodelete_;}; #endif//_thread_h_
Thread.cpp
#include "Thread.h" #include <iostream>using namespace std; Thread::thread (const threadfunc& func): Func_ (func), Autodelete_ (false) {}void Thread::start () {pthread_create ( &threadid_, NULL, Threadroutine, this);} void Thread::join () {Pthread_join (threadid_, NULL);} void* thread::threadroutine (void* Arg) {thread* Thread = static_cast<thread*> (ARG); Thread->run (); if (thread- >autodelete_) Delete Thread;return NULL;} void Thread::setautodelete (bool autodelete) {autodelete_ = Autodelete;} void Thread::run () {func_ ();}
Thread_test.cpp
#include "Thread.h" #include <boost/bind.hpp> #include <unistd.h> #include <iostream>using namespace Std;class foo{public:foo (int count): Count_ (count) {}void Memberfun () {while (count_--) {cout<< "This is a test ..." & Lt;<endl;sleep (1);}} void MemberFun2 (int x) {while (count_--) {cout<< ' x= ' <<x<< ' This is a test2 ... ' <<endl;sleep (1);}} int count_;}; void ThreadFunc () {cout<< "ThreadFunc ..." <<ENDL; void ThreadFunc2 (int count) {while (count--) {cout<< "ThreadFunc2 ..." <<endl;sleep (1);}} int main (void) {Thread T1 (threadfunc); Thread T2 (Boost::bind (THREADFUNC2, 3)); Foo foo (3); Thread T3 (Boost::bind (&foo::memberfun, &foo)); Foo Foo2 (3); Thread t4 (Boost::bind (&foo::memberfun2, &foo2,)); T1. Start (); T2. Start (); T3. Start (); T4. Start (); T1. Join (); T2. Join (); T3. Join (); T4. Join (); return 0;}
Instead of using the object-oriented programming style, use the boost bind/function to achieve this, which is the object-based programming style.
Object-based programming styles for C + + server development