Multithreaded programming learning notes-thread pool (i)

Source: Internet
Author: User

Take the multithreaded Programming learning note above-thread synchronization (i)

Take the multithreaded Programming learning note above-thread synchronization (ii)

Take the multithreaded Programming learning note above-thread synchronization (iii)

Creating multithreaded operations is very expensive, so each operation with a very short run time, creating multi-threaded operations, may not improve efficiency, but reduce efficiency.

If you have a very short execution time, it is appropriate to use the thread pool to increase efficiency rather than creating multithreading yourself.

The thread pool is where we allocate some resources to the pool, and when we need to use it, we get it from the pool, run out, and put it back in the pool.

. NET is managed by the CLR, the Theadtool class has a QueueUserWorkItem static method that accepts a delegate that represents a user-defined asynchronous operation that, after this method is called, enters the internal queue. If there are no threads in the pool, create a worker thread and put the first delegate in the worker thread. If you continue to put the delegate, the pool creates a new worker thread until the number of worker threads reaches the upper limit. When the delegate is placed, the new worker thread is not created, but waits in the queue until there are idle worker threads.

When all the operations in the thread pool are complete and there are no new task actions, the pool frees resources that are not used for long periods of time.

Note: It takes a short time to put an operation into the thread pool, not to put long-running operations into the thread pool, or to block worker threads. This will cause performance issues and very difficult to invoke issues.

Use thread pooling in ASP. Be careful, the thread pool in ASP. NET is a pooled thread pool, which causes the Web server to fail to serve normal HTTP requests if the worker threads in the thread pools are exhausted.

One, call the delegate in the thread pool

1. The code is as follows:

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading;namespacethreadpooldemo{ Public Delegate stringThreadpoolrun ( out intthreadId); classProgram {Static voidMain (string[] args) {Console.WriteLine ("start test thread pool-delegate ... "); intThreadId =0; Threadpoolrun Pooldele=Runthread; vart =NewThread (() = Runthread ( outthreadId));            T.start ();            T.join (); Console.WriteLine ("thread ID {0}", threadId); IAsyncResult R= Pooldele.begininvoke ( outThreadId, Callback,"Call callback function synchronously in thread pool"); stringresult = Pooldele.endinvoke ( outThreadId, R); Console.WriteLine ("worker thread ID in thread pool: {0}", threadId); Console.WriteLine ("return result: {0}", result); Thread.Sleep ( -);         Console.read (); }        Private Static voidCallback (IAsyncResult R) {Console.WriteLine ("start calling callback function ... "); Console.WriteLine ("the status of the callback function at this time: {0}", r.asyncstate); Console.WriteLine ("whether the thread that called this callback function is the online pool: {0}", Thread.CurrentThread.IsThreadPoolThread); Console.WriteLine ("The ID of the thread pool in which this callback function was called: {0}", Thread.CurrentThread.ManagedThreadId); }        Private Static stringRunthread ( out intthreadId) {Console.WriteLine ("Start working ... "); Console.WriteLine ("whether the thread that called this callback function is the online pool: {0}", Thread.CurrentThread.IsThreadPoolThread); Thread.Sleep (Timespan.fromseconds (2)); ThreadId=Thread.CurrentThread.ManagedThreadId; return string. Format ("ID of this thread pool in online: {0}", threadId); }    }} 

2. Program execution results such as.

When the above program runs, we first create the thread to perform the delegate operation, and then invoke the delegate's BeginInvoke to execute the callback method, which will be called after the asynchronous operation is completed, and a custom value will be passed to the callback function. Finally we get a result object that implements the IAsyncResult interface, allowing us to continue with other operations when the worker thread of the thread pool is working. We can poll the IsCompleted property of the result object to determine whether the operation is complete. You can also call EndInvoke to pass IAsyncResult to the delegate parameter.

Second, put the asynchronous operation in the thread pool

1. The code is as follows:

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading;namespacethreadpooldemo{classProgram {Static voidMain (string[] args) {Console.WriteLine ("start test thread pool-queueuserworkitem ... "); Const intx =1; Const inty =2; stringWorkstate ="Working status 2";            ThreadPool.QueueUserWorkItem (Asyncoper); Thread.Sleep ( +); ThreadPool.QueueUserWorkItem (Asyncoper,"Synchronization Status"); Thread.Sleep ( +); ThreadPool.QueueUserWorkItem (Status={Console.WriteLine ("operation status {0}", status); Console.WriteLine ("worker thread ID in thread pool: {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 ("worker thread ID in thread pool: {0}", Thread.CurrentThread.ManagedThreadId); Thread.Sleep (Timespan.fromseconds (2)); }, "Working Status"); Thread.Sleep ( -);        Console.read (); }        Private Static voidAsyncoper (Objectstatus) {Console.WriteLine ("operation Status: {0}", status??"NULL"); Console.WriteLine ("ID of worker thread pool in: {0}", Thread.CurrentThread.ManagedThreadId); Thread.Sleep ( -); }      }} 

2. The results of the implementation are as follows. The program was executed two times.

The program first defines a Asyncoper method, then uses QueueUserWorkItem to put this method into the thread pool and then puts it into a asyncoper method again, but this time it passes an object to the method call.

The Thread.Sleep method is called in the code to allow worker threads in the thread pool to be reused for new operations. Please note that the printed thradid, if ThreadID, proves that two operations have reused the same worker thread.

Multithreaded programming learning notes-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.