1, why do I need a thread pool? Some applications need to perform a number of small tasks, creating a thread for each task to complete, destroying the thread after the task is complete, and this creates a problem: when the task that is executed is T1 less than equals to the creation thread time T2 and destroys the thread time T3 sum T1<= T2 +T3, the responsiveness of application processing tasks can be greatly reduced, which affects application performance, and in order to solve such problems, thread pooling technology provides a good solution. The thread pool, as its name implies, is pooling the threads ' resources, creating an appropriate number of threads at the time of application startup, assigning a created thread from the thread pool when the task needs to be executed, executing the thread back, and destroying all the threads once the application is stopped. 2, the basic component of a thread pool A simple thread pool consists of at least the following components:1thread pool Manager (ThreadPool): for creating a thread pool object and managing the thread pool, such as assigning tasks to an idle thread, viewing the current thread state, and so on. 2worker Thread (workthread): Thread pool threads, may be suspended, may be assigned a task, if it is suspended, use a semaphore to block until a task is assigned. 3Task Interface (Task): an interface that each task must implement in order for the worker thread to schedule the task to execute. 3, the thread pool implementation under UNIX will show you the class of thread pool implementation, which contains more object-oriented design ideas. is mainly
One thread pool manages multiple worker classes, and each worker class object manages one thread.
1) Mutex: Mutex class with only one pthread_mutex_t private member, encapsulating POSIX mutex, followed by queue and stack for thread pool.
Mutex.h
1 #ifndef Mutex_h2 #defineMutex_h3 4#include <iostream>5#include <pthread.h>6 using namespacestd;7 8 classMutex9 {Ten Public: One Mutex (); A voidLock (); - voidUnlock (); - the Private: - pthread_mutex_t Mutex; - }; - + #endif
Linux C + + thread pool