Linux thread Pool __linux

Source: Internet
Author: User
/* Small Linux thread pool written by Luoxiongwei e-mail:luo6620378li@qq.com welcom to, bugs!
The next step is to add priority to the task in the work queue to implement a priority queue. * * #ifndef __threadpools #define __threadpools #include <sys/types.h> #include <pthread.h> #include <unis td.h> #include <vector> #include <cstdio> #include <cstdlib> #include <cstring> using Std::ve

ctor

struct task//Queue task node {void (*handler) (void *);//Task function void * data;//task Data//int prority;//task priority};
  struct work_queue_t//Task Force column {struct work_queue_t * next;
  struct work_queue_t * head;
  struct work_queue_t * tail;
struct task * elment;

}; Work Queue Operation work_queue_t * Init_work_queue ()//Initialize Work queue void Destory_work_queue ();//Destroy Work Queue work_queue_t * Remove_task ();//


Take the team first task int add_tast (Task * new_task);//Add task at the end of work queue bool Empty (); Thread pool resource void *thread_rounter (void *);//threading execution function struct work_queue_t * work_queue=null;//Task Force column int work_count=0;// Number of elements in the work queue vector<pthread_t> threads;//records the ID pthread_cond_t p of all threadsool_cond;//wake up the appropriate thread to start work pthread_mutex_t queue_lock;//protect work queues, and mutual exclusion resources in pools int idles;//idle threads int busy;//number of threads executing a task int max_ Maximum number of threads maintained in the thread;//pool bool to_exit;//destroy thread pool flag the bool validate;//thread pool is available/thread pool operation, four function void Thread_pool provided to user operations (int init_
  Threads_num);//build thread pool void Destroy_thread_pool ()//Destroy thread pool/* Assembly task handler and handler function parameters, note that once the task is complete, the data will be released by the system, so the next time you join a task to the thread pool, Please reassemble it.
Make sure that the handler function is thread-reentrant.
* * Task * Prod_task (void (*handler) (void *), void * data);

int Exec_task (Task * new_task)//left to the user's calling interface #endif//example of the work function void Task1 (void *arg);

    int main () {//Now tests 10 threads in the pool, 12 tasks.
  Task parameter char *ptr1= "I am Task one\n";
  Char *ptr2= "I am Task two\n";
  Char *ptr3= "I am Task three\n";
  Char *ptr4= "I am Task four\n";
  Char *ptr5= "I am Task five\n";
  Char *ptr6= "I am Task six\n";
  Char *ptr7= "I am Task seven\n";
  Char *ptr8= "I am Task eight\n";
  Char *ptr9= "I am Task nine\n";
  Char *ptr10= "I am Task ten\n";
  Char *ptr11= "I am Task eleven\n";

  Char *ptr12= "I am Task twltle\n"; Assemble Tasks Task * TASK_P1=prod_task (TASK1,PTR1);
  Task * Task_p2=prod_task (TASK1,PTR2);
  Task * Task_p3=prod_task (TASK1,PTR3);
  Task * Task_p4=prod_task (TASK1,PTR4);
  Task * Task_p5=prod_task (TASK1,PTR5);
  Task * Task_p6=prod_task (TASK1,PTR6);
  Task * Task_p7=prod_task (TASK1,PTR7);
  Task * Task_p8=prod_task (TASK1,PTR8);
  Task * Task_p9=prod_task (TASK1,PTR9);
  Task * Task_p10=prod_task (TASK1,PTR10);
  Task * Task_p11=prod_task (TASK1,PTR11);

  Task * Task_p12=prod_task (TASK1,PTR12);
  Thread_pool (10);//Create a thread pool in which up to 10 Threads//12 Task Exec_task (TASK_P1);
  Exec_task (TASK_P2);
  Exec_task (TASK_P3);
  Exec_task (TASK_P4);
  Exec_task (TASK_P5);
  Exec_task (TASK_P6);
  Exec_task (TASK_P7);
  Exec_task (TASK_P8);
  Exec_task (TASK_P9);
  Exec_task (TASK_P10);
  Exec_task (TASK_P11);

  Exec_task (TASK_P12); /* delay, let all tasks run out.
  It can also be done without delay, but the thread pool is destroyed if the task has not been completed.

 * * Sleep (20);
Destroy_thread_pool ()//Destroy thread pool return 0;
    } void Task1 (void *arg) {char *ptr= (char *) arg;
Write (Stdout_fileno,ptr,strlen (PTR)); }

//One of the external interfaces that is provided to the user, which generates task tasks * prod_task (void (*handler) (void *), void * data) {struct task * new_task=new task;

  if (!new_task) return NULL;
  new_task->handler=handler;
  new_task->data=data;
return new_task;
       The corresponding operation of the//Work queue work_queue_t * Init_work_queue () {work_queue_t *work_queue_=new work_queue_t;

      if (!work_queue_) return NULL;
      work_queue_->head=work_queue_->tail=null;
      work_queue_->next=null;
      work_queue_->elment=null;
      work_count=0;
return work_queue_;
  work_queue_t * Remove_task ()//Take the team first task {work_queue_t * TEMP;

    if (empty ())//Task force column null return null;
    temp=work_queue->head;
    work_queue->head=work_queue->head->next;
 work_count--;
return temp;

  ///Add tasks int add_tast (Task * new_task) {work_queue_t * temp=null to the end of work queue;
     if (empty ())//queue is empty {temp=new work_queue_t;
     temp->next=null;
    temp->elment=new_task;
    work_queue->head=work_queue->tail=temp;work_count++;
  return 0;
        } else//queue is not empty {temp=new work_queue_t;
        temp->next=null;
       temp->elment=new_task;
       work_queue->tail->next=temp;
       work_queue->tail=temp;
       work_count++;
  return 0;
  return-1;//add unsuccessful} void Destory_work_queue () {work_queue_t * temp;
         if (work_count!=0) {while (work_queue->head) {temp=work_queue->head;
         work_queue->head=work_queue->head->next;
         Delete temp->elment;
       Delete temp;

  }} bool Empty () {bool flage=false;

 if (work_count==0) flage=true;
return flage; }//thread pool operation//initialization thread pool void thread_pool (int init_threads_num) {pthread_mutex_init (&queue_lock,null);//Initialize lock if (PTH
  Read_cond_init (&pool_cond,null)!=0) return;
  Work_queue=init_work_queue ()//Task Force column if (!work_queue) return;
  Max_thread=init_threads_num;
  idles=0;
  busy=0;
  To_exit=false;

Validate=true; }

Destroy thread pools and work queues, condition variables, lock void Destroy_thread_pool () {pthread_mutex_lock (&queue_lock);
   changing condition to_exit=true;

    Validate=false;

     Cancels all threads in the thread pool for (size_t i=0;i!=threads.size (); ++i) Pthread_cancel (threads[i));
   Destroy Work queue destory_work_queue ();

    Pthread_mutex_unlock (&queue_lock);
   Destroy lock and Condition variable Pthread_mutex_destroy (&queue_lock);

Pthread_cond_destroy (&pool_cond);

    the int exec_task (Task * new_task) {pthread_t tid;
     Pthread_mutex_lock (&queue_lock);
       Adds a new task to the Work queue if (Add_tast (new_task)!=0) {pthread_mutex_unlock (&queue_lock);
     return-1; Pthread_cond_signal (&pool_cond);//Work queue has a task, wake-up a blocking thread//whether to create a new thread, depending on the condition of the IF (validate&&!to_exit&& amp; (idles==0| | (idles+busy) <max_thread)) {if (Pthread_create (&tid,null,thread_rounter,null)!=0) {Pthr
          Ead_mutex_unlock (&queue_lock);
        return-1;
 } threads.push_back (TID);//Record thread ID     idles++;//more than one idle thread pthread_mutex_unlock (&queue_lock);
    return 0;
   } pthread_mutex_unlock (&queue_lock);
return 0; } void *thread_rounter (void *) {Pthread_detach (pthread_self ());//Detach oneself pthread_setcancelstate (pthread_cancel_enable,
  NULL);

  Pthread_setcanceltype (pthread_cancel_deferred,null);//At the point of cancellation to cancel the thread work_queue_t * WORK_ITEM=NULL; for (;;)
       Check the work queue for work items {Pthread_mutex_lock (&queue_lock) that need to be handled; while (validate&&!to_exit&& (Work_item=remove_task ()) ==null))/The Task Force column is empty, it waits for pthread_cond_wait (&

      Amp;pool_cond,&queue_lock);//here will be a cancellation point pthread_mutex_unlock (&queue_lock); if (validate&&!to_exit&&work_item->elment->data) {Pthread_mutex_lock (&queue_l
             Ock);
           busy++;//the thread is busy idles--;

          Pthread_mutex_unlock (&queue_lock);

     Work_item->elment->handler (work_item->elment->data);//handler function call      Pthread_mutex_lock (&queue_lock);
             busy--;
           idles++;

             Pthread_mutex_unlock (&queue_lock);
              Release resource Delete work_item->elment;
        Delete Work_item;
} return NULL; }

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.