Introduction:
This time we re-encapsulate threads, using object-based programming, not for the way we redefine virtual functions in object-oriented programming, where we use callback functions.
Thread.h
1 #ifndef Thread_h_2 #defineThread_h_3 4#include <boost/noncopyable.hpp>5#include <functional>6#include <pthread.h>7 8 classthread:boost::noncopyable9 {Ten Public: Onetypedef std::function<void() >Threadcallback; A - Thread (Threadcallback callback); -~Thread (); the - voidstart (); - voidjoin (); - + Static void*runinthread (void*); - + Private: A pthread_t threadid_; at BOOLIsrunning_; -Threadcallback Callback_;//callback function - }; - - - in #endif //Thread_h_
Instead of redefining the virtual function, you can see that a function adapter is set up to hold the business logic we want.
You can call Callback_ directly with the static function Runinthread.
Thread.cpp
1#include"Thread.h"2 3 Thread::thread (Threadcallback callback)4: Threadid_ (0),5Isrunning_ (false),6 Callback_ (Std::move (callback))7 {8 9 }Ten Onethread::~Thread () A { - if(Isrunning_) - { the //Detach - Pthread_detach (threadid_); - } - } + - voidThread::start () + { APthread_create (&threadid_, NULL, Runinthread, This); atIsrunning_ =true; - } - voidThread::join () - { - Pthread_join (threadid_, NULL); -Isrunning_ =false; in } - to void*thread::runinthread (void*Arg) + { -Thread *pt = static_cast<thread*>(ARG); thePt->callback_ ();//Call callback function * $ returnNULL;Panax Notoginseng}
The above has a few experience to deal with, Google recommended when the thread this class destructor, if the threads have not finished, then detach.
and set a flag bit BOOL isrunning flag thread whether it starts.
Test code
1#include"Thread.h"2#include <stdio.h>3#include <unistd.h>4 using namespacestd;5 6 voidfoo ()7 {8 while(1)9 {Tenprintf"foo\n"); OneSleep1); A } - } - the - - intMainintargcChar Const*argv[]) - { +Thread T (&foo); - + T.start (); A T.join (); at - return 0; -}
As you can see, when using object-based programming, you do not need to define the user's own class, just pass in a function adapter in the main function. Specific function types can be implemented using bind.
Test Code 2
1#include"Thread.h"2#include <stdio.h>3#include <unistd.h>4 using namespacestd;5 6 classFoo7 {8 Public:9 voidFoointi)Ten { One while(1) A { -printf"Foo%d\n", i++); -Sleep1); the } - } - }; - + - + intMainintargcChar Const*argv[]) A { at Foo F; - inti = the; -Thread T (Bind (&foo::foo, &F, i)); - - T.start (); - T.join (); in - return 0; to}
For member functions of a class, use the big kill bind.
C + + Learning Path: Thread Encapsulation (object-based programming)