Multithreaded programming learning notes-thread pool (ii)

Source: Internet
Author: User

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

Third, thread pool and degree of parallelism

This example is the difference between learning how to apply a thread pool to implement a large number of operations, and working with creating a large number of threads.

1. The code is as follows

usingSystem;usingSystem.Collections.Generic;usingSystem.Diagnostics;usingSystem.Linq;usingSystem.Text;usingSystem.Threading;namespacethreadpooldemo{classProgram {Static voidMain (string[] args) {Console.WriteLine ("Start testing thread pool with self-created threads ... "); Const intTotal = -; LongMillisecondes =0; Stopwatch SW=NewStopwatch (); Sw.            Start ();            ThreadRun (total); Sw.            Stop (); Millisecondes=SW.            Elapsedmilliseconds; decimalMom = (decimal) (Environment.workingset/(1024x768*1024.0)); Sw.            Reset (); Sw.            Start ();            Threadpoolrun (total); Sw.            Stop (); Console.WriteLine ("self-created thread total time {0}, Memory: {1} MB", Millisecondes,mom); Console.WriteLine ("thread pool total time {0}, memory consumption: {1} MB", SW. Elapsedmilliseconds, Environment.workingset/(1024x768*1024.0));        Console.read (); }        Private Static voidThreadRun (intTotal ) {            using(varCountdown =Newcountdownevent (total)) {Console.WriteLine ("Start-Self-create thread ... ");  for(inti =0; I < total; i++)                {                    vart =NewThread (() ={Console.WriteLine ("self-creating thread ID: {0}", Thread.CurrentThread.ManagedThreadId); Thread.Sleep (Timespan.fromseconds (0.1)); Countdown. Signal ();//registers the signal with the countdownevent and decreases the value of the Currentcount.                     });                T.start (); } countdown.  Wait (); //blocks the current thread until the number of countdownevent signals changes to 0Console.WriteLine ("-----------------"); }        }        Private Static voidThreadpoolrun (intTotal ) {            using(varCountdown =Newcountdownevent (total)) {Console.WriteLine ("Start-thread pool ... ");  for(inti =0; I < total; i++) {ThreadPool.QueueUserWorkItem (_={Console.WriteLine ("thread pool worker thread ID: {0}", Thread.CurrentThread.ManagedThreadId); Thread.Sleep (Timespan.fromseconds (0.1)); Countdown. Signal ();//registers the signal with the countdownevent and decreases the value of the Currentcount.                     }); } countdown.  Wait (); //blocks the current thread until the number of countdownevent signals changes to 0Console.WriteLine ("-----------------"); }        }    }} 

2. Program operation results such as.

1) In this example, we created 500 threads ourselves, one for each thread, and 100 milliseconds for each thread. The total takes 11 seconds and consumes resources such as.

2) We use a thread pool to perform the same 500 operations. The total takes 9 seconds and consumes resources such as.

As can be seen from the comparison of 1 and 2), the self-created thread consumes more CPU resources than the thread pool.

Iv. canceling operations from the thread pool

How do we do this if we want to cancel the operation of a thread from the thread pool? This example uses the CancellationTokenSource and CancellationToken two classes to implement an operation in the cancel thread pool. These two are introduced in net 4.0.

1. Sample Code

usingSystem;usingSystem.Collections.Generic;usingSystem.Diagnostics;usingSystem.Linq;usingSystem.Text;usingSystem.Threading;namespacethreadpooldemo{classProgram {Static voidMain (string[] args) {Console.WriteLine ("to start the test thread pool, cancel the running thread ... "); using(varCTS =NewCancellationTokenSource ()) {CancellationToken token=CTS.                Token; ThreadPool.QueueUserWorkItem (_=Asyncoper (token)); Thread.Sleep (Timespan.fromseconds (2)); Cts. Cancel ();//canceling a thread operation            }            using(varCTS =NewCancellationTokenSource ()) {CancellationToken token=CTS.                Token; ThreadPool.QueueUserWorkItem (_=asyncoperation (token)); Thread.Sleep (Timespan.fromseconds (2)); Cts. Cancel ();//canceling a thread operation            }            using(varAT1 =NewCancellationTokenSource ()) {CancellationToken token=CTS.                Token; ThreadPool.QueueUserWorkItem (_=AsyncOper3 (token)); Thread.Sleep (Timespan.fromseconds (2)); Cts. Cancel ();//canceling a thread operation} thread.sleep (Timespan.fromseconds (2)); Console.WriteLine ("..... Cancel a running thread end ... ");        Console.read (); }        Private Static voidasyncoperation (CancellationToken token) {Try{Console.WriteLine ("Start--a second worker thread in the thread pool ... ");  for(inti =0; I <5; i++) {token. Throwifcancellationrequested ();//Gets the cancel request, throws the OperationCanceledException exception,Thread.Sleep (Timespan.fromseconds (1)); } Console.WriteLine ("the second worker in the-------thread pool finishes working----------"); }            Catch(OperationCanceledException ex) {Console.WriteLine ("Use the throw exception method to cancel the second worker thread Id:{0},{1}", Thread.currentthread.managedthreadid,ex.            Message); }        }        Private Static voidAsyncoper (CancellationToken token) {Console.WriteLine ("Start--the first worker thread in a thread pool ... ");  for(inti =0; I <5; i++)            {                if(token.) iscancellationrequested)//determine if the operation has been canceled{Console.WriteLine ("cancel worker thread id:{0} using polling method", Thread.CurrentThread.ManagedThreadId); return; } thread.sleep (Timespan.fromseconds (1)); } Console.WriteLine ("the first worker in the-------thread pool finishes working----------"); }        Private Static voidAsyncOper3 (CancellationToken token) {Console.WriteLine ("Start-A third worker thread in the thread pool ... "); BOOLCancel =false; Token. Register (()=>cancel =true);  for(inti =0; I <5; i++)            {                if(cancel)//determine if the operation has been canceled{Console.WriteLine ("Cancel the third worker thread by registering a callback function id:{0}", Thread.CurrentThread.ManagedThreadId); return; } thread.sleep (Timespan.fromseconds (1)); } Console.WriteLine ("the third worker in the-------thread pool is finished working----------"); }    }}

2. Running results such as.

This example implements a total of three ways to cancel operations in a thread pool.

    1. Polling checks the Cancellationtoken.iscancellationrequested property and, if true, indicates that the operation was canceled.
    2. Throws a Operationcancellationexception exception. This allows code outside the operation to cancel the operation.
    3. Registers a callback function where the thread pool invokes the callback function when the operation is canceled, and the benefit is that the cancellation logic is passed to another asynchronous operation.

Multithreaded programming learning notes-thread pool (ii)

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.