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

Source: Internet
Author: User

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

Multi-thread programming learning notes-Thread Pool (1)

 

Iii. Thread Pool and concurrency

This example shows how to apply a thread pool to implement a large number of operations, and how it differs from creating a large number of threads.

1. The Code is as follows:

Using System; using System. collections. generic; using System. diagnostics; using System. linq; using System. text; using System. threading; namespace ThreadPoolDemo {class Program {static void Main (string [] args) {Console. writeLine ("start testing thread pool and self-created thread... "); Const int total = 500; long millisecondes = 0; Stopwatch sw = new Stopwatch (); sw. start (); ThreadRun (total); sw. stop (); millisecondes = sw. elapsedMilliseconds; decimal mom = (decimal) (Environment. workingSet/(1024*1024.0); sw. reset (); sw. start (); ThreadPoolRun (total); sw. stop (); Console. writeLine ("Total time consumed by self-created threads {0}, memory occupied: {1} MB", millisecondes, mom); Console. writeLine ("Total thread pool time {0}, memory occupied: {1} MB", sw. ElapsedMilliseconds, Environment. workingSet/(1024*1024.0); Console. read ();} private static void ThreadRun (int total) {using (var countdown = new CountdownEvent (total) {Console. writeLine ("start -- self-created thread... "); For (int I = 0; I <total; I ++) {var t = new Thread () => {Console. writeLine ("self-created Thread ID: {0}", Thread. currentThread. managedThreadId); Thread. sleep (TimeSpan. fromSeconds (0.1); countdown. signal (); // register a Signal with CountdownEvent and reduce the value of CurrentCount. }); T. start ();} countdown. wait (); // blocks the current thread until the count of CountdownEvent signals changes to 0 Console. writeLine ("-----------------") ;}} private static void ThreadPoolRun (int total) {using (var countdown = new CountdownEvent (total) {Console. writeLine ("start -- thread pool... "); For (int I = 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 (); // register a Signal with CountdownEvent and reduce the value of CurrentCount. }) ;}Countdown. Wait (); // block the current thread until the count of CountdownEvent signals changes to 0 Console. WriteLine ("-----------------");}}}}

2. The program running result is shown in.

 

1) In this example, we have created 500 threads, each thread has one operation, and each thread is blocked for 100 milliseconds. It took 11 seconds in total, consuming resources such.

 

2) We use the thread pool to execute the same 500 operations. It takes 9 seconds to consume resources, for example.

 

From the comparison between 1) and 2), we can see that the self-created thread consumes more CPU resources than the thread pool.

 

4. Cancel operations from the thread pool

What should we do if we want to cancel the operation of a thread from the thread pool? In this example, the CancellationTokenSource and CancellationToken classes are used to cancel operations in the thread pool. These two are introduced in net 4.0.

1. Sample Code

Using System; using System. collections. generic; using System. diagnostics; using System. linq; using System. text; using System. threading; namespace ThreadPoolDemo {class Program {static void Main (string [] args) {Console. writeLine ("cancel a running thread from the thread pool to start testing... "); Using (var cts = new CancellationTokenSource () {CancellationToken token = cts. token; ThreadPool. queueUserWorkItem (_ => AsyncOper (token); Thread. sleep (TimeSpan. fromSeconds (2); cts. cancel (); // Cancel the thread operation} using (var cts = new CancellationTokenSource () {CancellationToken token = cts. token; ThreadPool. queueUserWorkItem (_ => AsyncOperation (token); Thread. sleep (TimeSpan. fromSeconds (2); cts. cancel (); // Cancel the thread operation} using (var cts = new CancellationTokenSource () {CancellationToken token = cts. token; ThreadPool. queueUserWorkItem (_ => AsyncOper3 (token); Thread. sleep (TimeSpan. fromSeconds (2); cts. cancel (); // Cancel the Thread operation} Thread. sleep (TimeSpan. fromSeconds (2); Console. writeLine (".......... Canceling the running thread ends ...... "); Console. Read () ;}private static void AsyncOperation (CancellationToken token) {try {Console. WriteLine (" -- the second worker thread in the thread pool... "); For (int I = 0; I <5; I ++) {token. throwIfCancellationRequested (); // gets the cancel request and throws an OperationCanceledException exception, Thread. sleep (TimeSpan. fromSeconds (1);} Console. writeLine ("------- the second worker thread in the thread pool has finished working ----------");} catch (OperationCanceledException ex) {Console. writeLine ("Use the thrown exception method to cancel the second worker Thread ID: {0}, {1}", Thread. currentThread. managedThreadId, ex. message) ;}} private static void AsyncOper (CancellationTok En token) {Console. WriteLine ("start -- the first worker thread in the thread pool... "); For (int I = 0; I <5; I ++) {if (token. isCancellationRequested) // determines whether the operation has been canceled {Console. writeLine ("using the polling method to cancel a working Thread ID: {0}", Thread. currentThread. managedThreadId); return;} Thread. sleep (TimeSpan. fromSeconds (1);} Console. writeLine ("------- the first worker thread in the thread pool finished working ----------");} private static void AsyncOper3 (CancellationToken token) {Console. writeLine ("start -- the third working thread in the thread pool... "); Bool cancel = false; token. register () => cancel = true); for (int I = 0; I <5; I ++) {if (cancel) // determine whether the operation has been canceled {Console. writeLine ("cancel the third working Thread ID: {0} by registering the callback function", Thread. currentThread. managedThreadId); return;} Thread. sleep (TimeSpan. fromSeconds (1);} Console. writeLine ("------- the third worker thread in the thread pool has finished working ----------");}}}

2. The running result is shown in.

 

This example provides three methods to cancel operations in the thread pool.

Related Article

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.