Using C++11 's function/bind component to encapsulate the use of thread and callback functions

Source: Internet
Author: User

Previously, in http://www.cnblogs.com/inevermore/p/4008572.html, a POSIX thread was encapsulated in an object-oriented manner, where a virtual function + inheritance was used, and the user overridden the thread base class's Run method , passing in their own user logic.

Now that we take the function of c++11 and use it as a member of the thread class, the user only needs to pass the function object to the thread, so the thread declaration should contain a function member variable.

The declaration of the class is as follows:

#ifndef Thread_h_#defineThread_h_#include<boost/noncopyable.hpp>#include<functional>#include<pthread.h>classthread:boost::noncopyable{ Public: typedef std::function<void() >Threadcallback;    Thread (Threadcallback callback); ~Thread (); voidstart (); voidjoin (); Static void*runinthread (void*);Private: pthread_t threadid_; BOOLIsrunning_; Threadcallback Callback_; //callback function};#endif //Thread_h_

So how do I turn on threads? Thinking with the previous agreement, write a static function, the user pthread_create the third parameter, this as the last parameter can be.

void Thread::start () {    pthread_create (this);     true ;}

callback function

Note that in this package, we use a callback function. The difference between a callback function and a normal function is that the normal function is called directly by us, and the function call is a way of accumulating constantly, and the callback function is usually that we pass a function into a "box", which is called by the mechanism inside the box.

In this example, we pass the function to the thread, and the thread executes the function object when the thread is started.

This mechanism is used extensively in Win32 programming, where we write functions for mouse clicks, double-click events, and then register them with the Windows system, and then the system calls the appropriate constructors, depending on the type of event, when we trigger various events.

For callback functions, refer to: http://www.zhihu.com/question/19801131

Later, there is time, and then a special summary of the callback function.

The complete CPP is as follows:

#include"Thread.h"Thread::thread (Threadcallback callback): Threadid_ (0), Isrunning_ (false), Callback_ (Std::move (callback)) {} Thread::~Thread () {if(isrunning_) {//DetachPthread_detach (THREADID_); }}voidThread::start () {pthread_create (&threadid_, NULL, Runinthread, This); Isrunning_=true;}voidThread::join () {Pthread_join (threadid_, NULL); Isrunning_=false;}void*thread::runinthread (void*Arg) {Thread*PT = static_cast<thread*>(ARG); PT->callback_ ();//Call callback function    returnNULL;}

There are three ways to use this thread:

One is to use the normal function as the callback function

void foo () {    while (1)    {        printf ("foo\n"  );        Sleep (1);}    } int Main (intcharConst *argv[]) {    Thread t (&  foo);    T.start ();    T.join ();     return 0 ;}

The second is to use the member function of the class as the callback function:

classfoo{ Public:    voidFoointi) { while(1) {printf ("Foo%d\n", i++); Sleep (1); }    }};intMainintargcChar Const*argv[])    {Foo F; inti = the; Thread T (Bind (&foo::foo, &F, i));    T.start ();    T.join (); return 0;}

The last one is to combine a new threading class, and note that this is a combination of classes:

classfoo{ Public: Foo (): Thread_ (Bind (&foo::foo, This))    {    }    voidstart () {Thread_.start ();    Thread_.join (); }    voidfoo () { while(1) {printf ("foo\n"); Sleep (1); }    }Private: Thread thread_;};intMainintargcChar Const*argv[])    {Foo F;    F.start (); return 0;}

There are some complex classes that need to be integrated in three ways, such as TimerThread, which is discussed later, which contains a thread and a timer, the user registers the logic with the timer, and the timer's start function is registered to thread.

The thread of this approach, the use of flexibility relative to the object-oriented style, improved a lot.

Object-based and object-oriented

Here are a few things to summarize:

Object-oriented relies on virtual function + inheritance , and the user realizes its own logic by overriding the virtual function of the base class.

Based on the combination of object-dependent classes, using function and bind to implement the delegation mechanism, more relies on the callback function incoming logic.

Using C++11 's function/bind component to encapsulate the use of thread and callback functions

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.