C + + simple thread pool

Source: Internet
Author: User

Demand

Previously written a C # version of the simple thread pool http://blog.csdn.net/ylbs110/article/details/51224979
Having just learned the future of the new c++11 feature, I thought of using it to implement a thread pool.

Implement

The main difference between the basic and C # versions is the implementation of the delegate, the different threading handles, and the thread Lock:

    • Originally C + + has a function template, but the implementation is more troublesome, here is mainly to implement the thread pool, so the dynamic parameters of the delegation is not implemented, directly using typedef
      void (*func) () to implement a function pointer with no parameter and no return value
    • Thread handle using future
    • Thread locks use mutexes

The use of the future and the mutex is very clear in the 2nd edition of the C + + standard library, not in detail here.
Similar to the implementation of the C # version, the first implementation of a thread handle class, which is mainly used to store the handle of the method running in the thread pool, and implementation of the method of closing operations, completion of state queries, loop State query and a series of functions.
The thread pool uses queues to store methods that are not yet running, and all threads are also stored with a single queue. All threads run a run method that is used primarily to extract the task from the thread handle queue and then run it. The method of extracting a task requires that the mutex lock be used to prevent conflicts when multiple threads extract the task.
The principle is very simple, on the code bar:

Publicdata

Public data files, this assembly only implements a Func pointer

#include "stdafx.h"void(*Func)();
Thread

Thread.h

#include "stdafx.h"#include <future>#include <chrono>#include "PublicData.h"using namespace STD;classthread{ Public: Thread (Func f =nullptr,intWaitTime =0,intCycletime =-1);voidSetfunc (Func F,intWaitTime =0,intCycletime =-1); Func Getfunc ();BOOLCancel ();BOOLIscancel ();BOOLIsDone ();voidRun ();Private:intWaitTime;intCycletime;BOOLIscycle =false;;BOOLIsRunning =false;BOOLIscancel =false;BOOLIsdone =false; Func _func;};

Thread.cpp

#include "StdAfx.h"#include "Thread.h"Thread:: Thread(Func f, int waitTime, int cycletime): _func (f), WaitTime (WaitTime), Cycletime (cycletime) {if(WaitTime< 0) WaitTime= 0;if(Cycletime<= 0) iscycle= false;}void Thread:: Setfunc(Func f, int waitTime, int cycletime) {_func=F This -WaitTime=WaitTime; This -Cycletime=Cycletime;}; FuncThread:: Getfunc(){return_func;}; boolThread:: Cancel(){if(Isdone)return false;Else if(Iscancel)return false;Else if(isrunning&& !Iscancel)return false;Else        returnIscancel= true;} boolThread:: Iscancel(){returnIscancel;} boolThread:: IsDone(){returnIsdone;}void Thread:: Run(){if(Isdone)return;if(_func==Nullptrreturn; This_thread:: Sleep_for(Chrono:: Milliseconds(WaitTime));if(Iscancel)return; IsRunning= true;if(iscycle) {        (*_func) (); This_thread:: Sleep_for(Chrono:: Milliseconds(Cycletime)); }Else(*_func) (); Isdone= true;}
ThreadPool

ThreadPool.h

#pragma once#include "stdafx.h"#include <deque>#include <chrono>#include <future>#include <mutex>#include <exception>#include "PublicData.h"#include "Thread.h"using namespace STD;classthreadpool{ Public: ThreadPool (inti =1);    ~threadpool (); Thread Create (Func F,intWaitTime =-1,intCycletime =-1);voidShoutdown ();BOOLIsshoutdown ();Private: deque<Thread>Threaddeque; deque<future<void>> futuredeque; Mutex Runmutex;intFuturenum; Func Getfunc ();voidRun ();};

ThreadPool.cpp

#include "stdafx.h"#include "ThreadPool.h"Threadpool::threadpool (inti) {Threaddeque = deque<Thread>(); Futuredeque = deque<future<void>> (); Futurenum = i; while(i-->0) {Futuredeque.push_back (Async (Launch::async, [ This]{//run ();             while(true)            {if(Threaddeque.size () >0){AutoR = Threaddeque.begin ()->getfunc ();                    Threaddeque.pop_front ();                R ();    }            }        })); }}; Threadpool::~threadpool () {}; Thread Threadpool::create (Func F,intWaitTime,intCycletime) {Threaddeque.push_back (Thread (f, WaitTime, cycletime));returnThreaddeque.back ();};voidThreadpool::shoutdown () { while(Futuredeque.size () >0) {Futuredeque.begin ()->~future ();    Futuredeque.pop_front (); } while(Threaddeque.size () >0) {Threaddeque.begin ()->cancel ();    Threaddeque.pop_front (); }};BOOLThreadpool::isshoutdown () {return! (Futuredeque.size () >0);}; Func Threadpool::getfunc () {lock_guard<mutex> L (Runmutex);AutoR = Threaddeque.begin ()->getfunc (); Threaddeque.pop_front ();returnR;};voidThreadpool::run () { while(true)    {if(Threaddeque.size () >0){AutoR = Threaddeque.begin ()->getfunc ();            Threaddeque.pop_front ();        R (); }               }};

Reprint Please specify source: http://blog.csdn.net/ylbs110/article/details/51337530

Test test Method
voidShowA () { for(inti =0; I < -; i++)printf("a");printf("\ n");}voidShowb () { for(inti =0; I < -; i++)printf("B");printf("\ n");}voidSHOWC () { for(inti =0; I < -; i++)printf("C");printf("\ n");}voidShowd () { for(inti =0; I < -; i++)printf("D");printf("\ n");}
called
    ThreadPool t=ThreadPool(5);    Thread a = t.create(showA);    Thread b = t.create(showB);    Thread c = t.create(showC);    Thread d = t.create(showD);    system("pause");    return 0;
Run Results
Aaaaaaaaaaaaaaaaaabaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa  AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCBBBBBBBBBBBBBBBBB please Press any key to continue ... Bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbaaaaccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc cccccccccccccccccccccaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb Bbbbccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc Ccccccccccccccccccccccccccaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaccccccccccccccccccccccccccc Ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb Bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbddddddddddddddddddddddddddddddddddddddddddddddddddddd Ddddddddddddddddddddddddddddcccccccccccccccbbbbbbbbbbbbbbbbbbbbbbbbdddddddddddddddddddddddddddddddddddddddddddddddddddddd Ddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd Ddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd Ddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd Ddcbbccccbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbccccccccccccccccccccccccccccccccccccccccc CcccccccccccccccccccccccccccccccCccccccccccccc 

As can be seen from the results, four threads execute output without sequencing and running successfully.

C + + simple thread pool

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.