Technical background of thread pool
In object-oriented programming, creating and destroying objects is time-consuming, because creating an object to acquire memory resources or other resources means that one way to improve the efficiency of the service program is to minimize the number of objects created and destroyed, especially those that are resource-intensive. How to use the existing object to serve is a key problem that needs to be solved, in fact, this is the reason that some "pooling resources" technology produces. For example, you are familiar with the database connection pool is to follow this idea, the thread pool technology described in this article also conforms to this idea.
How thread pooling technology can improve the performance of server programs
The server program I mentioned refers to a program that accepts requests from clients and can process requests, not just those that accept requests from network clients.
Multithreading technology mainly solves the problem of multiple threads in the processor unit, which can significantly reduce the idle time of the processor unit and increase the throughput capacity of the processor unit. However, if you use multithreading incorrectly, you increase the processing time for individual tasks. A simple example can be cited:
Assume that the time to complete a task on a single server is T
T1 the time the thread was created T2 the time that the task was executed in the thread, including the time required to synchronize between threads T3 the time the thread was destroyed
Obviously t = t1+t2+t3. Note that this is an extremely simplified hypothesis.
It can be seen that T1,T3 is the overhead of multithreading itself, and we are eager to reduce the time it takes to t1,t3, thus reducing t time. However, users of some threads do not notice this, so the threads are created or destroyed frequently in the program, which causes T1 and T3 to occupy a considerable proportion in T. Obviously this is the highlight of the thread's weakness (T1,T3), not the merit (concurrency).
Thread pooling technology is a technique that focuses on how to shorten or adjust t1,t3 time to improve the performance of server programs. It t1,t3 the start and end of the server program, or some idle time period, so that there is no t1,t3 overhead when the server program processes the client request.
The thread pool not only adjusts the time period generated by the T1,T3, but it also significantly reduces the number of threads created. Look at an example:
Suppose a server handles 50,000 requests a day, and each request requires a separate thread to complete. We compare the total number of threads that result from threading pool technology and the servers that are detrimental to thread pooling technology. Thread pooling, the number of threads is generally fixed, so the total number of threads does not exceed the number of threads in the thread pool or the upper limit (hereinafter referred to as the thread-pool size), and if the server does not utilize the thread pool to process these requests, the total number of threads is 50000. The general thread pool size is far less than 50000. Therefore, server programs that utilize the thread pool do not waste time processing requests in order to create 50000, thereby increasing efficiency.
These are assumptions that do not adequately explain the problem, and below I will discuss the simple implementation of the thread pool and compare the program to illustrate the advantages of threading technology and the areas of application.
Simple implementation and contrast test of thread pool
Typically a simple thread pool contains at least the following components.
Thread pool Manager (Threadpoolmanager): Used to create and manage thread pools
Worker thread (workthread): Thread pool threads
Task Interfaces (tasks): the interfaces that each task must implement to enable worker threads to schedule the execution of tasks.
Task queue: Used to hold tasks that are not processed. Provides a buffering mechanism.
Next I demonstrate the simplest thread pool. No optimizations were made.
Using system;using system.collections.generic;using system.linq;using system.text;using System.Collections;using System.Threading; Namespace threadmanager{public class Threadpoolmanager {private int maxthreadnum; private int minthreadnum; private int growstepnum; Number of threads public int threadnum{get;set;} Default number of threads public int Defaultthreadnum {get; set;} Private queue<task> Taskqueue; Private queue<workthread> workthreadlist; Public Threadpoolmanager (int i) {taskqueue = new queue<task> (); Workthreadlist = new queue<workthread> (); Defaultthreadnum = 10; if (i > 0) defaultthreadnum = i; Createthreadpool (i); Public Threadpoolmanager (): This (ten) {} public bool Isalltaskfinish () {RE Turn Taskqueue.count = = 0; } public void Createthreadpool (int i{if (workthreadlist = = null) Workthreadlist = new queue<workthread> (); Lock (Workthreadlist) {for (int j = 0; J < i;j++) {THR eadnum++; Workthread workthread = new Workthread (ref taskqueue,threadnum); Workthreadlist.enqueue (Workthread); }}} public void AddTask (task Task) {if (task = = null) Return Lock (Taskqueue) {taskqueue.enqueue (Task); }//monitor.enter (Taskqueue); Taskqueue.enqueue (Task); Monitor.Exit (Taskqueue); public void Closethread () {//object obj = null; while (Workthreadlist.count! = 0) {try {workthread Workthrea D = Workthreadlist.dequeue (); Workthread. Closethread (); Continue } catch (Exception) {} break; }}}}</workthread></workthread></task></workthread></task>
Worker thread Class
Using system;using system.collections.generic;using system.linq;using system.text;using System.Threading; Namespace threadmanager{public class Workthread {public int threadnum {get; set;} private bool Flag; Private queue<task> Taskqueue; Private task task; Public Workthread (ref queue<task> Queue, int. i) {this. Taskqueue = queue; Threadnum = i; Flag = true; New Thread (Run). Start (); } public void Run () {while (flag && taskqueue! = null) {//Get any Service Lock (Taskqueue) {try { task = Taskqueue.dequeue (); } catch (Exception) {task = null; } if (task = = null) continue; } try {task. SetEnd (FALSE); Task. StartTask (); } catch (Exception) {} try { if (!task. Isend ()) {task. SetEnd (FALSE); Task. Endtask (); }} catch (Exception) {}}//end of While} public void Closethread () {flag = false; The try {if (task! = null) task. Endtask (); } catch (Exception) {}}}}</task></task>
Task class and implementation class
Using system;using system.collections.generic;using system.linq;using system.text; namespace threadmanager{public interface Task {//<summary>//Set Flag of task. </summary> void SetEnd (BOOL flag); <summary>//Start task. </summary> void StartTask (); <summary>//End Task. </summary> void Endtask (); <summary>//Get Status of task. </summary>//<returns></returns> bool Isend (); }}using system;using system.collections.generic;using system.linq;using system.text;using System.Threading; Namespace threadmanager{public class Testtask:task {private bool is_end; public void SetEnd (BOOL flag) {is_end = flag; } public void StartTask () {Run (); } public void Endtask () { Is_end = true; Console.WriteLine (Thread.CurrentThread.ManagedThreadId + ":" + "End!) "); } public bool Isend () {return is_end; public void Run () {for (int i = 0; i < i++) {Console.Write Line (thread.currentthread.managedthreadid+ ":" +i); } } }}
The problem with this simple model is that a lot of the time it takes to get a task is constantly trying to make the performance drop very low, the need to improve the method is to add a semaphore mechanism, do not let the program idling!
In the next article I will optimize to make the thread pool truly more efficient!
The above is C # itself to implement thread pool function (a) content, more relevant content please pay attention to topic.alibabacloud.com (www.php.cn)!