Thread pool (i)

Source: Internet
Author: User
Tags pow static class

Meaning

The thread pool is a form of multithreading that adds tasks to the queue during processing, and then automatically starts those tasks after the thread is created. Thread pool threads are all background threads. Each thread uses the default stack size, runs at the default priority, and is in a multithreaded apartment. If a thread is idle in managed code, such as waiting for an event, the thread pool inserts another worker thread to keep all the processors busy. If all thread pool threads are always busy, but the queue contains pending work, the thread pool will create another worker thread after a period of time but the number of threads will never exceed the maximum value. Threads that exceed the maximum value can be queued, but they will not start until other threads have finished.

Component server programs The use of threading technology to respond to customer requests is commonplace, and you may think that this is already a high efficiency, but have you ever thought about optimizing the way you use threading. This article will show you how the server program optimizes performance with line pool and provides a simple thread pool implementation. 1. Thread pool Manager (Threadpoolmanager): Used to create and manage thread pool 2, worker threads (workthread): Thread pool threads 3, task interfaces (tasks): interfaces that each task must implement to enable worker threads to schedule the execution of tasks. 4. Task queue: Used to store tasks that are not processed. Provides a buffering mechanism. Technical background in object-oriented programming, creating and destroying objects is time-consuming, because creating an object acquires memory resources or other resources. More so in Java, virtual machines will attempt to track each object so that it can be garbage collected after the object is destroyed. So one way to improve the efficiency of the service process is to minimize the number of objects created and destroyed, especially the resource-intensive object creation and destruction. 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. At present, some famous big companies are particularly bullish on this technology, and have already applied the technology in their products. For example, IBM's Websphere,iona Orbix 2000 in Sun's Jini, Microsoft's MTS (Microsoft Transaction Server 2.0), COM +, and so on. A feature application can have multiple threads that take a lot of time to wait for an event to occur in hibernation. Other threads may go to sleep, and only periodically wake up to change or update status information, and then go into hibernation again. To simplify the management of these threads. NET Framework provides a thread pool for each process, a thread pool has several waiting operations, and when a wait operation completes, the worker thread in the thread pools executes the callback function. Threads in a thread pool are managed by the system, and programmers do not have to struggle with thread management to focus on application tasks.

when not to use thread pool threads:If you need to have a task with a specific priority if you have a task that might run long (and therefore block other tasks) if you need to place the thread in a single-threaded apartment (threads in the thread pool are in a multithreaded apartment) if you need a permanent identity to identify and control the thread, For example, if you want to use a dedicated thread to terminate it, Suspend it or find it by name the System.threadingpool class implements the thread pool, which is a static class that provides a series of methods for managing threads Threading.queueuseritem method creates a thread pool threads in the thread pools to execute the specified method (with a delegate Waitcallba CK), and queues the thread into the thread pool for execution.
1 publicstaticBooleanQueueUserWorkItem(WaitCallback wc,Object state);
Passing parameters to a task procedure can be passed to the task procedure in such a way that the passed-in argument to the object type parameter is passed to the QueueUserWorkItem. If a task procedure requires more than one parameter, you can define the class that contains the data and cast it to the object data type. Application scope 1, requires a large number of threads to complete the task, and the time to complete the task is relatively short. It is very appropriate to use thread pooling techniques to perform tasks such as Web server requests. Because a single task is small and the number of tasks is huge, you can imagine the number of clicks on a popular website. But for long-time tasks, such as a Telnet connection request, the thread pool's advantages are not obvious. Because the Telnet session time is much larger than the thread's creation time. 2, for the performance of demanding applications, such as requiring the server to respond quickly to customer requests. 3, accept a sudden large number of requests, but not so that the server resulting in a large number of threading applications. Sudden large number of customer requests, in the absence of a thread pool, will generate a large number of threads, although theoretically most of the operating system threads maximum is not a problem, a short period of time to produce a large number of threads may cause memory to reach the limit, and the "OutOfMemory" error occurs.
1 //Line Pooling Example2 using System;3 using System.Threading;4  5  Publicclasstest6 {7     //field that holds the numeric value to be computed8     Static DoubleNumber1 =-1;9     Static DoubleNumber2 =-1;Ten   One      Public Static voidMain () A     { -         //gets the maximum number of threads for the thread pool and the minimum number of idle threads maintained -         intMaxthreadnum, Minthreadnum; the         intPortthreadnum; -           - Threadpool.getmaxthreads (out Maxthreadnum, out portthreadnum); - Threadpool.getminthreads (out Minthreadnum, out portthreadnum); +Console.WriteLine ("Maximum number of threads: {0}", maxthreadnum); -Console.WriteLine ("Minimum number of threads: {0}", minthreadnum); +           A         //function Variable Value at         intx=15600; -         //Start the first task: Calculate the x 8-Time Square -Console.WriteLine ("Start the first task: Calculate 8 times for {0}.") ", x); -ThreadPool.QueueUserWorkItem (NewWaitCallback (TaskProc1), x); -           -         //Start a second task: Calculate the 8 root of x inConsole.WriteLine ("Start the second task: Calculate the 8 root of the {0}.") ", x); -ThreadPool.QueueUserWorkItem (NewWaitCallback (TASKPROC2), x); to           +         //wait until two values are calculated -          while(Number1 = =-1 | | number2 = =-1); the         //Print Calculation Results *Console.WriteLine ("Y ({0}) = {1}", X, Number1 +number2); $ Console.read ();Panax Notoginseng     } -       the     //Start the first task: Calculate the x 8-Time Square +     Static voidTaskProc1 (object o) A     { theNumber1 = Math.pow (convert.todouble (o), 8); +     } -       $     //Start a second task: Calculate the 8 root of x $     Static voidTaskProc2 (object o) -     { -Number2 = Math.pow (convert.todouble (o), 1.0/8.0); the     } -}
Line Pooling Example
1[HostProtection (securityaction.linkdemand,synchronization=true, externalthreading=true)]2  3  Public Static classThreadPool4 {5[Obsolete ("Threadpool.bindhandle (INTPTR) hasbeendeprecated. Pleaseusethreadpool.bindhandle (SafeHandle) instead. ",false), SecurityPermission (securityaction.demand,flags=SecurityPermissionFlag.UnmanagedCode)]6  Public Staticbool Bindhandle (IntPtr oshandle)7 {8     if(Oshandle = =NULL){Throw NewArgumentNullException ("Oshandle");}9BOOL flag =false;TenBOOL Success =false; One runtimehelpers.prepareconstrainedregions (); A     Try -     { - Oshandle.dangerousaddref (ref success); theFlag =bindiocompletioncallbacknative (Oshandle.dangerousgethandle ()); -     } -     finally -     { +         if(Success) - oshandle.dangerousrelease (); +     } A     returnFlag; at}
Pool Structure

Thread pool (i)

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.