C # thread pool for multithreading learning [threadpool]

Source: Internet
Author: User
ArticleDirectory
    • Threadpool. setmaxthreads Method

In the multi-threadedProgramIn, there are usually two situations:

One case:In an application, the thread spends most of its time waiting for an event to respond.
This is generally solved using threadpool;

Another situation:The thread is always in sleep state, but is periodically awakened.
Timer (timer) is generally used to solve this problem;

This article only talks about the thread pool [threadpool]

Threadpool msdn help: http://msdn.microsoft.com/zh-cn/library/system.threading.threadpool.aspx#Y0

Add a task to the thread pool:

Threadpool. queueuserworkitem (New waitcallback (method name ));

Heavy Load

Threadpool. queueuserworkitem (New waitcallback (method name), parameter );

Threadpool is a static class, so it does not need to be instantiated.

 

The main control of the thread pool controls the number of threads:

Threadpool. setmaxthreads Method
 
Public static bool setmaxthreads (INT workerthreads, int completionportthreads)

Parameters:

Workerthreads
Type: system. int32

The maximum number of auxiliary threads in the thread pool.

Completionportthreads
Type: system. int32

The maximum number of asynchronous I/O threads in the thread pool.

Example:

Using system; using system. collections. generic; using system. LINQ; using system. text; using system. threading; namespace multi-thread pool test {class program {public static void main () {threadpool. setmaxthreads (3, 3); For (INT I = 0; I <50; I ++) {thr T = new Thr (); threadpool. queueuserworkitem (New waitcallback (T. threadproc), I);} console. writeline ("breakpoint test"); thread. sleep (1, 100000); console. writeline ("Running ended");} public class thr {public void threadproc (object I) {console. writeline ("thread [" + I. tostring () + "]"); thread. sleep (1000 );}}}}

Output result:

You will find that the breakpoint test is on top. Why?

Cause:

1. Thread Pool startup and termination is not what our program can control, I don't know anyway, if you know, you can mail me henw@163.com

2. There is no return value after the threads in the thread pool are executed.

In a word, we don't know what the thread pool has done. How can we solve the task completion problem?

The operating system provides manualresetevent)

Manualresetevent allows threads to communicate with each other by sending signals. Generally, this communication involves the tasks that a thread must complete before other threads perform. When a thread starts an activity (this activity must be completed before other threads can start), it calls reset to put manualresetevent in a non-terminating State, which can be considered to control manualresetevent. The thread that calls waitone on manualresetevent will stop and wait for the signal. When the control thread completes the activity, it calls set to send a signal waiting for the thread to continue. And release all the waiting threads. Once it is terminated, manualresetevent will remain terminated (that is, the thread that calls waitone will return immediately and will not block it) until it is manually reset. You can pass a Boolean value to the constructor to control the initial status of manualresetevent. If the initial status is terminated, the value is true; otherwise, the value is false.

For details, see msdn: http://msdn.microsoft.com/zh-cn/library/system.threading.manualresetevent.aspx

Mainly used

Eventx. waitone (timeout. Infinite, true); blocks the current thread until the current waithandle receives the signal.

Eventx. Set (); sets the event state to the terminated state, allowing one or more threads to continue.

modified program:

Using system; using system. collections. generic; using system. LINQ; using system. text; using system. threading; namespace multi-thread pool test {class program {public static void main () {// create a manualresetevent object and initialize it to manualresetevent eventx = new manualresetevent (false); threadpool. setmaxthreads (3, 3); thr T = new Thr (15, eventx); For (INT I = 0; I <15; I ++) {threadpool. queueuserworkitem (New waitcallback (T. threa Dproc), I);} // wait for the event to complete, that is, the thread calls manualresetevent. Set () method // eventx. waitone to stop the current thread until the current waithandle receives the signal. Eventx. waitone (timeout. infinite, true); console. writeline ("breakpoint test"); thread. sleep (1, 10000); console. writeline ("Running ended");} public class thr {public Thr (INT count, manualresetevent MRE) {imaxcount = count; eventx = MRE;} public static int icount = 0; public static int imaxcount = 0; Public manualresetevent eventx; Public void threadproc (object I) {console. writeline ("thread [" + I. tostring () + "]"); THR EAD. sleep (2000); // interlocked. the increment () operation is an atomic operation. For details, refer to the following description for icount ++. // The atomic operation cannot be interrupted or snatched by a higher level. Since you have raised this question, I 'd like to put it further. // Because the operating system is interrupted most of the time, // a program may be interrupted by a thread with a higher priority during execution. // Some operations cannot be interrupted. Otherwise, the restoration will fail. At this time, these operations require atomic operations. // An operation that cannot be interrupted. Interlocked. increment (ref icount); If (icount = imaxcount) {console. writeline ("sends an end signal! "); // Set the event status to the terminated state, allowing one or more threads to wait for the task to continue. Eventx. Set ();}}}}}

Output result:

The order is normal.

Program source code: multi-thread pool test. Zip

Welcome to join us!

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.