C # Thread (V): thread pool

Source: Internet
Author: User

from: http://kb.cnblogs.com/page/42531/

In multi-threaded programs, there are often two situations:

One scenario: In an application, a thread spends most of its time waiting for an event to occur before it can respond

This is generally solved by using threadpool (thread pool);

Another scenario: The line accesses tile is dormant, but is periodically awakened

This is usually solved by using a timer (timer);

The ThreadPool class provides a system-maintained thread pool (which can be seen as a container for a thread) that requires more than Windows 2000 system support, because some of these methods call API functions that are only available in higher versions of Windows.

Placing threads in the online pool requires the ThreadPool.QueueUserWorkItem () method, which is prototyped as follows:

Puts a thread into the thread pool, and the start () method of the threads invokes the function represented by the WaitCallback proxy object

public static bool QueueUserWorkItem (WaitCallback);

The overloaded method is as follows, and the parameter object is passed to the method represented by WaitCallback

public static bool QueueUserWorkItem (WaitCallback, object);

The ThreadPool class is a static class, and you cannot and do not have to build its objects. And once a project is added to the thread pool using this method, the item cannot be canceled.

Here you don't have to build a thread yourself, just write the work you want to do as a function, and then pass it on as a parameter to the ThreadPool.QueueUserWorkItem () method, and the way to pass is to rely on the WaitCallback proxy object, while the thread is built, managed, The operation is done automatically by the system, you do not have to consider the complex details of the problem.

Usage of ThreadPool:

First the program creates a ManualResetEvent object, which is like a semaphore that can use its signal to notify other threads.

In this example, when all the threads in the thread pool have finished working, the ManualResetEvent object is set to signaled to inform the main thread to continue running.

There are several important ways to ManualResetEvent objects:

When the object is initialized, the user can specify its default state (signal/no signal);

After initialization, the object will remain in its original state until its reset () or set () method is called:

Reset () Method: Set it to no signal state;

Set () Method: sets it to a signaled state.

WaitOne () Method: Causes the current thread to hang until the ManualResetEvent object is signaled, and the thread is activated. The program then adds work items to the thread pool, which are provided as functions by the system to initialize the automatically created thread. When all the threads have run out, the Manualresetevent.set () method is called, because the Manualresetevent.waitone () method is called and the main thread in the wait state receives the signal, and then it goes down, Finish the work behind it.

Example of ThreadPool usage:

usingSystem;usingSystem.Collections;usingSystem.Threading;namespacethreadexample{//This is the data structure used to hold the information, which is passed as a parameter     Public classSomestate { Public intcookies;  PublicSomestate (intIcookie) {Cookie=Icookie; }    }     Public classAlpha { PublicHashtable Hashcount;  PublicManualResetEvent Eventx;  Public Static intICount =0;  Public Static intImaxcount =0;  PublicAlpha (intMaxCount) {Hashcount=NewHashtable (MaxCount); Imaxcount=MaxCount; }//Thread constructor will call the Beta () method     Public voidBeta (Object state) {//outputs the hash code value of the current thread and the value of the cookieConsole.WriteLine ("{0} {1}:", Thread.CurrentThread.GetHashCode (), ((somestate) state).      Cookies); Console.WriteLine ("hashcount.count=={0}, Thread.CurrentThread.GetHashCode () =={1}", Hashcount.count, Thread.CurrentThread.GetHashCode ()); Lock(hashcount) {//If there is no hash value for the current thread in the current hash table, add the          if(!Hashcount.containskey (Thread.CurrentThread.GetHashCode ())) Hashcount.add (Thread.CurrentThread.GetHashCode (),0); Hashcount[thread.currentthread.gethashcode ()]=             ((int) Hashcount[thread.currentthread.gethashcode ()]) +1; }          intIX = -;          Thread.Sleep (IX); //The interlocked.increment () operation is an atomic operation, please see below for detailsInterlocked.Increment (refiCount); if(ICount = =Imaxcount)        {Console.WriteLine (); Console.WriteLine ("Setting Eventx");        Eventx.set (); }}} Public classSimplepool { Public Static intMain (string[] args) {Console.WriteLine ("Thread Pool Sample:"); BOOLW2K =false; intMaxCount =Ten;//allow up to 10 threads to run in a thread pool//creates a new ManualResetEvent object and initializes it to a signal-free StateManualResetEvent Eventx =NewManualResetEvent (false); Console.WriteLine ("Queuing {0} items to Thread Pool", MaxCount); Alpha Oalpha=NewAlpha (MaxCount); //Create a work item//Note Initialize the Eventx property of the Oalpha objectOalpha.eventx =Eventx; Console.WriteLine ("Queue to Thread Pool 0"); Try                {                    //to load a work item into the thread pool//There are APIs that are available in Windows 2000 or later, so notsupportexception exceptions can occurThreadPool.QueueUserWorkItem (NewWaitCallback (Oalpha.beta),NewSomestate (0)); W2K=true; }                Catch(NotSupportedException) {Console.WriteLine ("These API ' s may fail when called on a non-windows system."); W2K=false; }                if(W2K)//if the current system supports ThreadPool methods.                {                     for(intiitem=1; IItem < maxcount;iitem++)                    {                        //inserting a queue elementConsole.WriteLine ("Queue to Thread Pool {0}", IItem); ThreadPool.QueueUserWorkItem (NewWaitCallback (Oalpha.beta),Newsomestate (IItem)); } Console.WriteLine ("waiting for Thread Pool to drain"); //waits for the event to complete, that is, the thread calls the Manualresetevent.set () methodEventx.waitone (Timeout.infinite,true); //the WaitOne () method causes the thread that calls it to wait until the Eventx.set () method is calledConsole.WriteLine ("Thread Pool has been drained (Event fired)");                    Console.WriteLine (); Console.WriteLine ("Load Across Threads"); foreach(ObjectOinchOAlpha.HashCount.Keys) Console.WriteLine ("{0} {1}", O, Oalpha.hashcount[o]);                } console.readline (); return 0; }        }    }}
View CodeWhere the program should draw attention:

The Somestate class is a data structure that holds information, which is passed to each thread as a parameter in the program, because you need to encapsulate some useful information for the thread, which is very effective.

The Interlocked class that appears in the program is also designed for multithreaded programs, and it provides some useful atomic manipulation.

Atomic operation: In a multithreaded program, if the thread calls this operation to modify a variable, the other thread cannot modify the variable, which is essentially the same as the lock keyword.

Output Result:

Thread Pool sample:queuingTenitems to thread poolqueue to thread Pool0Queue to Thread Pool1Queue to Thread Pool2Queue to Thread Pool3Queue to Thread Pool4Queue to Thread Pool5 2 0: Hashcount.count==0, Thread.CurrentThread.GetHashCode () = =2Queue to Thread Pool6Queue to Thread Pool7Queue to Thread Pool8Queue to Thread Pool9Waiting forThread Pool to drain4 1: Hashcount.count==1, Thread.CurrentThread.GetHashCode () = =4 6 2: Hashcount.count==1, Thread.CurrentThread.GetHashCode () = =6 7 3: Hashcount.count==1, Thread.CurrentThread.GetHashCode () = =7 2 4: Hashcount.count==1, Thread.CurrentThread.GetHashCode () = =2 8 5: Hashcount.count==2, Thread.CurrentThread.GetHashCode () = =8 9 6: Hashcount.count==2, Thread.CurrentThread.GetHashCode () = =9 Ten 7: Hashcount.count==2, Thread.CurrentThread.GetHashCode () = =Ten  One 8: Hashcount.count==2, Thread.CurrentThread.GetHashCode () = = One 4 9: Hashcount.count==2, Thread.CurrentThread.GetHashCode () = =4Setting eventxthread Pool has been drained (Event fired) Load across threads One 1Ten 19 18 17 16 14 22 2
View Code

We should thoroughly analyze the above procedure, grasp the essence of the thread pool, understand the meaning of its existence, so as to use it with ease.

------------------>>>

 

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.