C + + simple thread pool implementation

Source: Internet
Author: User

Thread pool, in short, there is a bunch of threads that have been created (the maximum number is certain), initially they are idle, when a new task comes in, an idle thread processing task is taken out of the thread pool, and then when the task is processed, the thread is put back into the thread pool for other tasks to use. When the threads in the thread pool are working on the task, there is no idle thread to use, and if a new task is generated, you can wait for the thread end task to be idle to execute, and the following is the work diagram of the thread pool:

Why do we use thread pools?

In simple terms, the thread itself has overhead, we use multithreading to do task processing, single-threaded also can not abuse, the open new thread to the system will generate a lot of consumption, and the thread is a reusable resource, do not need to initialize every time, so you can use a limited number of threads to deal with unlimited tasks.

Nonsense less to say, directly on the code

The first is a state that encapsulates a condition variable and a mutex to protect the state of the thread pool

Condition.h

#ifndef _condition_h_
#define _condition_h_

#include <pthread.h>

//encapsulates a mutex and condition variable as state
typedef struct condition
{
    pthread_mutex_t Pmutex;
    pthread_cond_t Pcond;
} condition_t;

The operation function of the state
int condition_init (condition_t *cond);
int Condition_lock (condition_t *cond);
int Condition_unlock (condition_t *cond);
int condition_wait (condition_t *cond);
int condition_timedwait (condition_t *cond, const struct TIMESPEC *abstime);
int condition_signal (condition_t* cond);
int Condition_broadcast (condition_t *cond);
int Condition_destroy (condition_t *cond);

#endif

Condition.c

#include "condition.h"//initialization int condition_init (condition_t *cond) {int status;
    
    if (status = Pthread_mutex_init (&cond->pmutex, NULL)) return status;
    
    if (status = Pthread_cond_init (&cond->pcond, NULL)) return status;
return 0;

}//Lock int condition_lock (condition_t *cond) {return pthread_mutex_lock (&cond->pmutex);}

unlock int condition_unlock (condition_t *cond) {return pthread_mutex_unlock (&cond->pmutex);}

Wait for int condition_wait (condition_t *cond) {return pthread_cond_wait (&cond->pcond, &cond->pmutex);} Fixed time waits for int condition_timedwait (condition_t *cond, const struct TIMESPEC *abstime) {return pthread_cond_timedwait (&A
Mp;cond->pcond, &cond->pmutex, abstime);

//Wake up a sleep thread int condition_signal (condition_t* cond) {return pthread_cond_signal (&cond->pcond);} Wakes up all sleep thread int condition_broadcast (condition_t *cond) {return Pthread_cond_broadcast (&cond->pcond);
    }//Free int Condition_destroy (condition_t *cond) {int status;
    
    if (status = Pthread_mutex_destroy (&cond->pmutex)) return status;
        
    if (status = Pthread_cond_destroy (&cond->pcond)) return status;
return 0; }

Then the thread pool corresponds to the threadpool.h and THREADPOOL.C

#ifndef _thread_pool_h_
#define _THREAD_POOL_H_

//thread pool header file

#include "condition.h"

// Encapsulates the task object that the object in the thread pool needs to perform a
typedef struct task
{
    void * (*run) (void *args);  function pointer, the task that needs to be performed is
    void *arg;              Parameter
    struct task *next;      The next task in the task queue
}task_t;


Below is the thread pool structure
typedef struct ThreadPool
{
    condition_t ready;    State quantity
    task_t *first;       The first task in the task queue
    task_t *last;        The last task in the task Queue
    int counter;         Thread pool has the number of threads
    int idle;            The number of Kongxi threads in the thread pool
    int max_threads;     Thread pool max thread number
    int quit;            Whether to exit the flag
}threadpool_t;


The thread pool initializes
the void Threadpool_init (threadpool_t *pool, int threads);

Add Task
void Threadpool_add_task to Thread pool (threadpool_t *pool, void * (*run) (void *arg), void *arg);

Destroys the thread pool
void Threadpool_destroy (threadpool_t *pool);

#endif
 #include" threadpool.h "#include <stdlib.h> Include <stdio.h> #include <string.h> #include <errno.h> #include <time.h>//created thread execution void *threa
    D_routine (void *arg) {struct Timespec abstime;
    int timeout;
    printf ("Thread%d is starting\n", (int) pthread_self ());
    threadpool_t *pool = (threadpool_t *) arg;
        while (1) {timeout = 0;
        Additional lock Condition_lock (&pool->ready) is required before accessing the thread pool;
        Idle pool->idle++;
            Wait queue has task arrival or received thread pool destroy notification while (Pool->first = = NULL &&!pool->quit) {//otherwise thread blocking wait printf ("Thread%d is waiting\n 

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.