Thread Pool Code (General edition)

Source: Internet
Author: User

First, the application scenario

First, it must be made clear that the thread pool is not omnipotent and that it has its own specific usage scenarios. The thread pool is used to reduce the impact of the overhead on the application performance of the threads themselves, but only if the cost of creating and destroying the thread itself is not negligible compared to the overhead of the thread execution task . If the cost of creating and destroying the thread itself is negligible for the performance of the application, then using/not using the thread pool does not have much effect on the performance of the program.

The thread pool is typically suitable for several scenarios:

①, unit time processing tasks are frequent, and task time is short

②, high demand for real-time. If you receive a task and then create a thread, you may not be able to meet the requirements for real-time, and you must use a thread pool.

③, must often face high-burst events. such as Web servers. If there is a football broadcast, the server will have a huge impact, when using traditional methods, you must constantly create and destroy threads. This can be avoided by using a dynamic thread pool.

Second, the Code implementation

2.1 Header Files

#if!defined (__thread_pool_h__) #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <memory.h> #include <pthread.h> #include <sys/types.h>//boolean type typedef int  BOOL; #define FALSE (0) #define TRUE (1)/* thread Task List */typedef struct _thread_worker_t{void * (*process) (void *arg);                    /* thread-handling tasks */void *arg; /* Task interface parameter */struct _thread_worker_t *next;/* next node */}thread_worker_t;/* thread pool object */typedef struct{pthread_mutex_t Queue_   Lock   /* Queue mutex lock */pthread_cond_t Queue_ready;        /* Queue condition lock */thread_worker_t *head;               /* Task Queue header pointer */bool Isdestroy;          /* Whether the thread */pthread_t *threadid has been destroyed;                      /* Thread ID array-Dynamically allocate space */int num;               /* Number of threads */int queue_size; /* Task column current size */}thread_pool_t;/* function declaration */extern int Thread_pool_init (thread_pool_t **pool, int num); extern int Thread_pool_ Add_worker (thread_pool_t *pool, void * (*process) (void *arg), void *arg), extern int Thread_pool_destroy (thread_pool_t *pool); #endif/*__thread_pool_h__*/ 

  

2.2 Function implementation

/************************************************************* * *  ENERGY: Initialization of thread pool * * Parameter  : * *    Pool: Thread Pool Object * *    num: Thread pool number of threads * * return value: 0: Success! 0: Failure *************************************************************/int Thread_pool_ Init (thread_pool_t **pool, int num) {int idx = 0;        /* Allocate space for thread pool */*pool = (thread_pool_t*) calloc (1, sizeof (thread_pool_t)), if (NULL = = *pool) {return-1;}        /* Initialize thread pool */pthread_mutex_init (& (*pool)->queue_lock), NULL);p Thread_cond_init (& ((*pool)->queue_ Ready), NULL);(*pool)->head = null, (*pool)->num = num; (*pool)->queue_size = 0; (*pool)->isdestroy = false; (* Pool)->threadid = (pthread_t*) calloc (1, num*sizeof (pthread_t)), if (NULL = = (*pool)->threadid) {free (*pool);(* Pool) = null;return-1;}        /* Create thread */for (idx=0; idx<num; idx++) {pthread_create (& (*pool)->threadid[idx]), NULL, Thread_routine, * Pool);} return 0;}

  

/************************************************************* * * Power  : Join a task to the thread pool processing queue * * Parameters  : * *    Pool: Thread Pool Object * *    process: Task to be processed * *    parameter of arg:process function * * return value: 0: Success! 0: Failure ***************************************** /int Thread_pool_add_worker (thread_pool_t *pool, void * (*process) (void *arg), void *arg) {Thread_ worker_t *worker=null, *member=null;worker = (thread_worker_t*) calloc (1, sizeof (thread_worker_t)); if (NULL = = worker) { return-1;} worker->process = Process;worker->arg = Arg;worker->next = Null;pthread_mutex_lock (& (Pool->queue_ Lock)); member = POOL->HEAD;IF (null! = Member) {while (null! = member->next) member = Member->next;member-> Next = worker;} Else{pool->head = worker;} pool->queue_size++;p Thread_mutex_unlock (& (Pool->queue_lock));p thread_cond_signal (& (pool-> Queue_ready)); return 0;}

  

/************************************************************* * * Power  : Destruction of thread pool * * Parameter  : * *    Pool: Thread Pool Object * * Return value: 0: Success! 0: Failure *************************************************************/int Thread_pool_destroy (Thread_pool_ T *pool) {int idx = 0;thread_worker_t *member = null;if (false! = Pool->isdestroy) {return-1;} Pool->isdestroy = True;pthread_cond_broadcast (& (Pool->queue_ready)); for (idx=0; idx<pool->num; idx+ +) {Pthread_join (Pool->threadid[idx], NULL);} Free (pool->threadid);p Ool->threadid = Null;while (NULL! = pool->head) {member = Pool->head;pool->head = Member->next;free (member);} Pthread_mutex_destroy (& (Pool->queue_lock));p Thread_cond_destroy (& (Pool->queue_ready)), free (pool) ; return 0;}

  

/************************************************************* * * Power  : Thread pool entry function for individual threads * * Parameter  : * *    ARG: Thread Pool Object * * Return value: 0: Success! 0: Failed *************************************************************/static void *thread_routine (void *arg ) {thread_worker_t *worker = null;thread_pool_t *pool = (thread_pool_t*) arg;while (1) {Pthread_mutex_lock (& (pool- >queue_lock), while (false = = Pool->isdestroy) && (0 = = pool->queue_size)) {pthread_cond_wait (& ( Pool->queue_ready), & (Pool->queue_lock));} if (false! = Pool->isdestroy) {pthread_mutex_unlock (& (Pool->queue_lock));p thread_exit (NULL);} Pool->queue_size--;worker = Pool->head;pool->head = Worker->next;pthread_mutex_unlock (& (pool-> Queue_lock));                /* Execute the task in the queue */(* (worker->process)) (Worker->arg); free (worker); worker = NULL;}}

General code: https://www.cnblogs.com/cthon/p/9097007.html

Difficulty Upgrade Code: https://www.cnblogs.com/cthon/p/9085623.html

Thread Pool Code (General edition)

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.