C + + implements a simple thread pool _c language

Source: Internet
Author: User

C + + thread pool, inherit cdoit, implementation of which start and end

Header file

/* Multithreading Management * */#ifndef cthreadpoolmanage_h #define CTHREADPOOLMANAGE_H #include <iostream> #include <pth read.h> #include <unistd.h> #include <list> #include <vector> #include <time.h> #include <
asm/errno.h> #define USLEEP_TIME #define CHECK_TIME 1 using namespace std;
 Class Cdoit {public:virtual int start (void *) {};
virtual int end () {};
 
 
};  Class Cthreadpoolmanage {Private:int _minthreads;  Keep at least several threads int _maxthreads;      Can have a maximum of several threads int _waitsec; 
   How many seconds to idle will turn the thread off class threadinfo{Public:threadinfo () {isbusy = false;
  Doflag = true;
  }//pthread_mutex_t Mtx=pthread_mutex_initializer;
  pthread_cond_t Cond=pthread_cond_initializer;   BOOL IsBusy;
  whether free bool Doflag;     time_t BeginTime; Thread does not work start time pthread_t cthreadpid; Thread ID pthread_attr_t cthreadattr;         Thread Properties Cdoit * doit;        Task class void * value;
 The value to be passed};
 thread function static void* startthread (void*); Task Queue Lock PThread_mutex_t _duty_mutex;
 Task Queue list<threadinfo*> _dutylist;
 Thread queue lock pthread_mutex_t _thread_mutex;
  
Thread Queue list<threadinfo*> _threadlist; 
Initialize, create a minimum number of threads///void Initthread ();
Task assignment thread///static void* taskallocation (VOID*ARG);
pthread_t Tasktpid;
Thread destroy, stateful check thread///static void* checkthread (void* Arg);
pthread_t Checktpid;
 
BOOL Checkrun;
 
Thread exception exits clean static void Threadcleanup (void* arg);
 
int Addthread (list<threadinfo*> *plist,threadinfo* ptinfo);
Public:cthreadpoolmanage ();
* * Reserved minimum thread, maximum number of threads, idle how long to destroy, keep several threads redundant/cthreadpoolmanage (int min,int max,int waitsec);
 
~cthreadpoolmanage ();
int start ();
 
Task Injector int Putduty (cdoit *,void *);
 
int Getnowthreadnum ();
 
};

 #endif//Cthreadpoolmanage_h

CPP file

* * thread pool, Threading management class */#include "cthreadpoolmanage.h" Cthreadpoolmanage::cthreadpoolmanage () {_minthreads = 5;  Minimum number of threads _maxthreads = 5;      Can have a maximum of several threads _waitsec = 10;
 Idle number of seconds after the thread is closed Pthread_mutex_init (&_duty_mutex, NULL);
 Pthread_mutex_init (&_thread_mutex, NULL);
Checkrun = true;
  Cthreadpoolmanage::cthreadpoolmanage (int min, int max, int waitsec) {cthreadpoolmanage ();  _minthreads = min;  Keep at least a few threads _maxthreads = max;      Can have a maximum of several threads _waitsec = waitsec; How many seconds to idle turn the thread off} cthreadpoolmanage::~cthreadpoolmanage () {} void Cthreadpoolmanage::threadcleanup (void* arg) {thread
 info* tinfo = (threadinfo*) arg;
 Tinfo->isbusy = false;
 Pthread_mutex_unlock (&AMP;TINFO-&GT;MTX);
 Pthread_attr_destroy (&AMP;TINFO-&GT;CTHREADATTR);
Delete Tinfo;
 } void* Cthreadpoolmanage::startthread (void* Arg) {cout<< "thread started work" <<endl;
 threadinfo* tinfo = (threadinfo*) arg;
 Pthread_cleanup_push (THREADCLEANUP,ARG); while (Tinfo->doflag) {Pthread_mutEx_lock (&AMP;TINFO-&GT;MTX);
   if (Tinfo->doit = = NULL) {cout<< "Start waiting for task" <<endl;
   Pthread_cond_wait (&AMP;TINFO-&GT;COND,&AMP;TINFO-&GT;MTX);
  cout<< "Got a job." <<endl;
  } Tinfo->isbusy = true;
  Tinfo->doit->start (Tinfo->value);
  Tinfo->doit->end ();
  tinfo->doit=null;
  Tinfo->isbusy = false;
  Time (&tinfo->begintime);
 Pthread_mutex_unlock (&AMP;TINFO-&GT;MTX);
 //0 Normal execution Here does not perform cleanup functions, the exception executes Pthread_cleanup_pop (0);
 Pthread_attr_destroy (&AMP;TINFO-&GT;CTHREADATTR);
 Delete Tinfo;
cout<< "Thread End" <<endl;
 } void Cthreadpoolmanage::initthread () {int i = 0;
   for (i = 0;i<this->_minthreads;i++) {threadinfo *tinfo = new Threadinfo;
   Tinfo->doit = NULL;
   Tinfo->value = NULL;
   Tinfo->isbusy = false;
  Tinfo->doflag = true;
   Pthread_create_detached (Detach thread) and PTHREAD _create_joinable (non-detached threads) pthread_attr_init (&tinfo->cthreadattr); Pthread_attr_setdetachstate (&tinfo->cthreadattr,pthread_create_detached);
   cout<< "Initialization of a thread" <<endl; if (Pthread_create (&tinfo->cthreadpid,&tinfo->cthreadattr,startthread, (void *) Tinfo)!= 0) {cout<& lt; "
  Create thread Failed "<<endl;
  Break
 } this->_threadlist.push_back (Tinfo); } int Cthreadpoolmanage::addthread (std::list< cthreadpoolmanage::threadinfo* >* plist, CthreadPoolManage::
   threadinfo* ptinfo) {threadinfo *tinfo = new Threadinfo;
   Tinfo->doit = ptinfo->doit;
   Tinfo->value = ptinfo->value;
   Tinfo->isbusy = true; if (Pthread_create (&tinfo->cthreadpid,null,startthread, (void *) Tinfo)!= 0) {cout<< ' Create thread failed ' <<
  Endl
  return-1;
  } plist->push_back (Tinfo);
return 0;
 int cthreadpoolmanage::p utduty (cdoit* doit, void* value) {threadinfo *tinfo = new Threadinfo;
 Time (&tinfo->begintime);
 Tinfo->doit= doit;
 Tinfo->value = value;
  Pthread_mutex_lock (&_duty_mutex); This->_dutylist.push_back (tinfo);
 Pthread_mutex_unlock (&_duty_mutex);
return 0;
 } void* cthreadpoolmanage::taskallocation (void*arg) {cthreadpoolmanage * ptmanage = (cthreadpoolmanage*) arg;
 int size_1 = 0;
 int size_2 = 0;
 int i_1 = 0;
 int i_2 = 0;
 bool A_1 = true;
 bool a_2 = true;
 threadinfo* Ptinfo;
 threadinfo* ptinfotmp;
   while (true) {size_1 = 0;
   size_2 = 0;
   Pthread_mutex_lock (&ptmanage->_duty_mutex);
   Pthread_mutex_lock (&ptmanage->_thread_mutex);
   Size_1 = Ptmanage->_dutylist.size ();
   Size_2 =ptmanage->_threadlist.size (); for (List<threadinfo*>::iterator itorti1 = Ptmanage->_dutylist.begin (); Itorti1!=ptmanage->_
   Dutylist.end ();)
  {ptinfo = *itorti1;
  A_1 = true; for (List<threadinfo*>::iterator Itorti2 = Ptmanage->_threadlist.begin (); itorti2!=ptmanage->_
   Threadlist.end (); itorti2++) {ptinfotmp = *itorti2;
   if (Ebusy = = Pthread_mutex_trylock (&AMP;PTINFOTMP-&GT;MTX)) {continue;
 } if (!ptinfotmp->isbusy) {   Ptinfotmp->doit = ptinfo->doit;
    Ptinfotmp->value = ptinfo->value;
    Ptinfotmp->isbusy = true;
    Pthread_cond_signal (&ptinfotmp->cond);
    Pthread_mutex_unlock (&AMP;PTINFOTMP-&GT;MTX);
    A_1 = false;
    Delete Ptinfo;
   Break
    } pthread_mutex_unlock (&AMP;PTINFOTMP-&GT;MTX); } if (a_1) {if (Ptmanage->_threadlist.size () >ptmanage->_maxthreads| |
    Ptmanage->addthread (&ptmanage->_threadlist,ptinfo)!=0) {itorti1++;
   Continue
   }else{itorti1 = ptmanage->_dutylist.erase (ITORTI1);
    } Delete ptinfo;
    }else{itorti1 = ptmanage->_dutylist.erase (ITORTI1);
   } pthread_mutex_unlock (&ptmanage->_duty_mutex);
   Pthread_mutex_unlock (&ptmanage->_thread_mutex);
 Usleep (Usleep_time);
return 0;
 } void* Cthreadpoolmanage::checkthread (void* arg) {cthreadpoolmanage * ptmanage = (cthreadpoolmanage*) arg;
 threadinfo* Ptinfo;
 time_t Nowtime; while (Ptmanage->checkrun) {SLEEP (Check_time);
  Pthread_mutex_lock (&ptmanage->_thread_mutex);
  if (Ptmanage->_threadlist.size () <=ptmanage->_minthreads) {continue; for (List<threadinfo*>::iterator Itorti2 = Ptmanage->_threadlist.begin (); itorti2!=ptmanage->_
   Threadlist.end ();) {ptinfo = *itorti2;
   if (Ebusy = = Pthread_mutex_trylock (&ptinfo->mtx)) {itorti2++;
  Continue
  } time (&nowtime);  if (Ptinfo->isbusy = = False && nowtime-ptinfo->begintime>ptmanage->_waitsec) {Ptinfo->doflag =
   False
  Itorti2 = Ptmanage->_threadlist.erase (ITORTI2);
  }else{itorti2++;
  } pthread_mutex_unlock (&AMP;PTINFO-&GT;MTX);
 } pthread_mutex_unlock (&ptmanage->_thread_mutex);
 } int Cthreadpoolmanage::start () {//initializing this->initthread (); Start Task Assignment Thread if (Pthread_create (&tasktpid,null,taskallocation, (void *) this)!= 0) {cout<< "Create task assignment thread failed" <&lt
  ; Endl;
  return-1; //Create a current state assignment management thread if (pthread_create &AMp;checktpid,null,checkthread, (void *) this)!= 0 {cout<< "Create thread state allocation management thread failure" <<endl;
  return-1;
return 0;
 }///////////////////////////////int Cthreadpoolmanage::getnowthreadnum () {int num = 0;
  Pthread_mutex_lock (&this->_thread_mutex);
 num = This->_threadlist.size ();
 Pthread_mutex_unlock (&this->_thread_mutex);
return num;
 }

The above mentioned is the entire content of this article, I hope you can enjoy.

Please take a moment to share the article with your friends or leave a comment. We will sincerely thank you for your support!

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.