Multithreading programming learning notes-Thread Pool (1), multithreading programming learning notes

Source: Internet
Author: User

Multithreading programming learning notes-Thread Pool (1), multithreading programming learning notes

Multi-thread programming learning notes-thread synchronization (1)

Multi-thread programming learning notes-thread synchronization (2)

Multi-thread programming learning notes-thread synchronization (3)

 

 

Creating multiple threads is very expensive. Therefore, creating multiple threads for each operation with a very short running time may not improve the efficiency, but reduce the efficiency.

If you have a lot of very short-lived operations, it is suitable for improving the efficiency of the thread pool, rather than creating multiple threads on your own.

Thread Pool, that is, we first allocate some resources to the pool. When we need to use it, we will get it from the pool, use it out, and then put it back into the pool.

. The thread pool in. NET is managed by CLR. The TheadTool class has a QueueUserWorkItem static method. This static method accepts a delegate, representing a user-defined asynchronous operation, after this method is called, the delegate enters the internal queue. If there is no thread in the pool, create a working thread and put the first delegate into the working thread. If the task continues to be put into the delegate, a new working thread is created in the pool until the number of working threads reaches the upper limit. Then, put the task in the delegate, instead of creating a new working thread, but waiting in the queue until there is a idle working thread.

When all operations in the thread pool are completed and no new task operations are performed, the thread pool releases resources that are not used for a long time.

Note: The operation in the Thread Pool takes a short time. Do not put the operation that requires a long time to run into the thread pool or block the working thread. This will cause performance problems and very difficult to call.

In ASP. NET to use the thread pool, ASP. the thread pool in. NET is a shared thread pool. If all worker threads in the thread pool are used up, the WEB server cannot provide services for normal HTTP requests.

 

1. Call the delegate in the thread pool

1. The Code is as follows:

Using System; using System. collections. generic; using System. linq; using System. text; using System. threading; namespace ThreadPoolDemo {public delegate string ThreadPoolRun (out int threadId); class Program {static void Main (string [] args) {Console. writeLine ("start testing thread pool-delegate... "); Int threadId = 0; ThreadPoolRun poolDele = RunThread; var t = new Thread () => RunThread (out threadId); t. start (); t. join (); Console. writeLine ("thread ID {0}", threadId); IAsyncResult r = poolDele. beginInvoke (out threadId, Callback, "synchronously calling Callback function in thread pool"); string result = poolDele. endInvoke (out threadId, r); Console. writeLine ("Thread Pool worker thread ID: {0}", threadId); Console. writeLine ("returned result: {0}", result); Thread. slee P (2000); Console. Read ();} private static void Callback (IAsyncResult r) {Console. WriteLine ("start to call the Callback function... "); Console. writeLine ("Status of the callback function at this time: {0}", r. asyncState); Console. writeLine ("Whether the Thread that calls this callback function is in the Thread pool: {0}", Thread. currentThread. isThreadPoolThread); Console. writeLine ("the ID of the Thread that calls this callback function in the Thread pool: {0}", Thread. currentThread. managedThreadId);} private static string RunThread (out int threadId) {Console. writeLine ("Getting started... "); Console. writeLine ("Whether the Thread that calls this callback function is in the Thread pool: {0}", Thread. currentThread. isThreadPoolThread); Thread. sleep (TimeSpan. fromSeconds (2); threadId = Thread. currentThread. managedThreadId; return string. format ("ID of the thread in the thread pool: {0}", threadId );}}}

2. The execution result of the program is as follows.

 

When the above program runs, we first create a thread to execute the delegate operation, and then call the ininvoke of the delegate to execute the callback method. This callback function will be called after the asynchronous operation is completed, A custom value will be passed to the callback function. Finally, we will get a result object that implements the IAsyncResult interface. When the worker thread in the thread pool is working, allow us to continue other operations. We can poll the IsCompleted attribute of the result object to determine whether the operation is complete. You can also call EndInvoke to pass IAsyncResult to the delegate parameter.

 

Ii. Put the thread pool into asynchronous operations

1. The Code is as follows:

Using System; using System. collections. generic; using System. linq; using System. text; using System. threading; namespace ThreadPoolDemo {class Program {static void Main (string [] args) {Console. writeLine ("start testing thread pool-QueueUserWorkItem... "); Const int x = 1; const int y = 2; string workState =" working state 2 "; ThreadPool. queueUserWorkItem (AsyncOper); Thread. sleep (1000); ThreadPool. queueUserWorkItem (AsyncOper, "synchronization status"); Thread. sleep (1000); ThreadPool. queueUserWorkItem (status => {Console. writeLine ("Operation status {0}", status); Console. writeLine ("Thread Pool worker Thread ID: {0}", Thread. currentThread. managedThreadId); Thread. sleep (TimeSpan. fromSeconds (2);}, "working status "); ThreadPool. queueUserWorkItem (_ => {Console. writeLine ("Operation Result x + y = {0}, {1}", x + y, workState); Console. writeLine ("Thread Pool worker Thread ID: {0}", Thread. currentThread. managedThreadId); Thread. sleep (TimeSpan. fromSeconds (2) ;}, "working status"); Thread. sleep (1, 2000); Console. read ();} private static void AsyncOper (object status) {Console. writeLine ("Operation status: {0}", status ?? "Null"); Console. writeLine ("ID of the worker Thread in the Thread pool: {0}", Thread. currentThread. managedThreadId); Thread. sleep (2000 );}}}

2. The execution result is as follows. The program is executed twice.

The program first defines an AsyncOper method, then uses QueueUserWorkItem to put this method into the thread pool, and then puts it into an AsyncOper method again, but this time it calls the method to pass an object.

The Thread. sleep method is called in the code to reuse the worker threads in the Thread pool for new operations. Note the printed ThradId. If the ThreadID is the same, the two operations reuse the same worker thread.

 

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.