Thread series 06: view the thread pool and Its thread through CLR code, 06clr

Source: Internet
Author: User

Thread series 06: view the thread pool and Its thread through CLR code, 06clr


In "thread generation 04, passing data to the thread, thread naming, thread Exception Handling, thread pool", we know that each process has a thread pool. You can use TPL, ThreadPool. QueueUserWorkItem to delegate interaction with the thread pool. Experience this article: view the CLR code to observe the thread pool and its threads.

□View thread pools and threads by encoding

 

Use the static method of ThreadPool QueueUserWorkItem to put the thread into the thread pool to view the thread pool thread and main program thread execution.

    class Program
    {
        static void Main(string[] args)
        {
Console. WriteLine ("starting from the main thread ");
            for (int i = 0; i < 5; i++)
            {
                ThreadPool.QueueUserWorkItem(SayHello, i);
            }
Console. WriteLine ("main thread ended ");
        }
        static void SayHello(object arg)
        {
            int n = (int) arg;
Console. WriteLine ("the parameter received by thread {0} is: {1}, whether it is a background thread: {2 }",
                Thread.CurrentThread.ManagedThreadId,
                n,
                Thread.CurrentThread.IsBackground);
        }       
    }

○ The thread used to add the QueueUserWorkItem Method to the thread pool is a background thread.
○ Once the main thread ends, the background thread ends.
○ In the for statement block of the main program, two threads have been created and executed.

 

Let the main thread and thread pool thread Sleep for a period of time.

   class Program
    {
        static Random r = new Random();
        static void Main(string[] args)
        {
Console. WriteLine ("starting from the main thread ");
            for (int i = 0; i < 5; i++)
            {
                ThreadPool.QueueUserWorkItem(SayHello, i);
            }
            Thread.Sleep(r.Next(250, 500));
Console. WriteLine ("main thread ended ");
        }
        static void SayHello(object arg)
        {
            Thread.Sleep(r.Next(250, 500));
            int n = (int) arg;
Console. WriteLine ("the parameter received by thread {0} is: {1}, whether it is a background thread: {2 }",
                Thread.CurrentThread.ManagedThreadId,
                n,
                Thread.CurrentThread.IsBackground);
        }       
    }

○ The thread in the thread pool is still a background thread
○ After the main thread is Sleep for a period of time, the thread pool thread can be executed before the main thread ends.

 

Let the main thread Sleep for a longer period of time.

        static void Main(string[] args)
        {
Console. WriteLine ("starting from the main thread ");
            for (int i = 0; i < 5; i++)
            {
                ThreadPool.QueueUserWorkItem(SayHello, i);
            }
            Thread.Sleep(r.Next(1000, 3000));
Console. WriteLine ("main thread ended ");
        }

 

When the main thread Sleep takes longer, more threads in the thread pool will be executed.

 

□Use "instant window" to view thread pools and threads in CLR

 

It is inconvenient to view the thread pool and thread by encoding. We can use "SOS debugging extension" in "instant window" to observe the thread pool and thread in CLR.

→ Place a breakpoint in "Thread. Sleep (r. Next (1000,300 0 )"
→ Click "start"
→ When the code runs to the breakpoint, click "debug" -- "window" -- "instant" to open the "instant window"
→ Input the following command to load "SOS debugging extension"

For how to use "SOS debugging extension", refer to "Debug and view CLR Running code ".
→ Enter the following command to view the thread pool

○ Worker Thread displays the Thread status in the current Thread pool
○ Work Request in Queue display threads in the current Queue
→ Run the following command to view all threads:

○ MTA (Finalizer) indicates the thread recycled by GC
○ MTA (Threadpool Worker) indicates the thread in the thread pool.

 

□View all thread types on the CLR hosting Stack

 

→ Run the following command to view all thread types on the CLR managed Stack:

 

□View the thread pool instance on the CLR hosting Stack

 

→ Locate System. ThreadPoolWorkQueue and copy the MT code above it.
→ Enter the following command to view the heap address and quantity of the thread pool instance.

 

□View the address of the CLR managed Thread Pool

 

→ Copy the managed heap address of System. Threading. ThreadPoolWorkQueue
→ Enter the following command to view the address of the CLR managed Thread Pool

 

The thread series includes:

Thread series 01, front-end thread, back-end thread, thread synchronization thread series 02, multiple threads simultaneously process a time-consuming task to save time thread series 03, multi-thread shared data, multi-thread data sharing

Thread series 04: pass data to the thread, name the thread, handle thread exceptions, thread pool thread series 05, and manually end thread series 06. view the thread pool and its threads through CLR code.

 


C # how to determine whether all threads in the thread pool have been completed

// Method of checking the thread pool private voidCheckThreadPool (object state, bool timeout) {int workerThreads = 0; int maxWordThreads = 0; // int compleThreads = 0; ThreadPool. getAvailableThreads (out workerThreads, out compleThreads); ThreadPool. getMaxThreads (out maxWordThreads, out compleThreads); // when the number of available threads is equal to the maximum number of threads in the pool, it indicates that all threads in the thread pool have completed if (workerThreads = maxWordThreads) {// when this method is executed, the CheckThreadPool will no longer execute rhw. unregister (null); // The processing code after all threads are added here }}

How does java obtain the number of threads being executed in the thread pool?

Map map = Thread. getAllStackTraces ();
System. out. println (map. size ());
Put these two sentences in the required method, and you can get the result by running them.
The following is an explanation of java api:
Thread class.
GetAllStackTracespublic static Map <Thread, StackTraceElement []> getAllStackTraces () returns a ing of stack traces of all active threads. The ing key is a Thread, and each ing value is a StackTraceElement array, which indicates the stack dump of the corresponding Thread. The format of the returned stack trace is specified for the getStackTrace method.
While calling this method, the thread may also be executing. Each stack trace of a thread represents only one snapshot, and each stack trace can be obtained at different times. If the virtual machine does not have the stack trace information of the thread, a zero-length array is returned in the ing value.
If a security manager is available, call its checkPermission method through RuntimePermission ("getStackTrace") Permission and RuntimePermission ("modifyThreadGroup") permission to check whether stack tracing of all threads can be obtained.

I hope the above information will help you.

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.