Let's take a look at the ThreadPool source code and see another method for passing values between threads. threadpool source code

Source: Internet
Author: User

Let's take a look at the ThreadPool source code and see another method for passing values between threads. threadpool source code

 

These days I have been too busy to write a blog. Today I went home and simply read the ThreadPool source code. I found a funny thing called "execution context", which is called: "ExecutionContext".

 

I. general process of ThreadPool.

 

Step 1: it will call the underlying helper method.

 

Step 2: walk into this helper method and we will find that there is a queue, and the item of this queue must be an instance of QueueUserWorkItemCallback, which then inspires my

Interested. Let's see what QueueUserWorkItemCallback actually has?

 

Step 3: When you go to the QueueUserWorkItemCallback instance, the callback and state parameters will be given to the fields of the current class in sequence. What is interesting is that

ExecutionContext. IsFlowSuppressed () to determine whether to give the "context of the current thread" to the "calling thread"? This is explained later. Then we can see

IThreadPoolWorkItem. ExecuteWorkItem () method, which has a ContextCallback delegate call. Maybe this is to be called in every item in the queue.

.

 

Step 4: Then let's go back to the ThreadPoolGlobals. workQueue. Enqueue (callback, true) method in step 2 and check whether our callback and state are encapsulated

QueueUserWorkItemCallback is put into the queue. From this Enqueue method, we can see this. EnsureThreadRequested () and go to the method.

Later, I am eager to see the ThreadPool. RequestWorkerThread () method at this time, but it is an extern method, but in terms of name, it is to request the worker thread to execute, so

There is no real discovery of the so-called thread pool. (Because you cannot view the whole picture, you may not be right about it)

 

Well, the above analysis is probably like this. In fact, all the methods are encapsulated into a class at the bottom layer in a queue. We should use the above for selecting idle working threads to execute us.

There is a lot of code in the task, which is complicated and cannot be understood at the moment.

 

Ii. Execution Context

The third step just said "execution context". We can see that there is an if condition in this method, and then we can see that there is an ExecutionContext. IsFlowSuppressed () method.

It can be seen that it is called "blocking the flow". If it is not, Capture will be used to Capture the "context information" of the current thread. Then we can look down in a simple way. From this perspective, we followed

Capture the "Security Settings", "host Settings", "synchronization information", and "logical call" of the call thread. If logicalCallContext has a value, a copy operation is performed.

 

In fact, this logicalCallContext is very interesting. It contains a KV structure, which is also described in the source code. As long as I do not use IsFlowSuppressed, the context of the main thread will flow

Working thread, how can I set logicalCallContext? In fact, LogicalSetData and LogicalGetData in CallContext in C # can be used to do these tasks.

1 class Program 2 {3 static void Main (string [] args) 4 {5 CallContext. logicalSetData ("name", "ctrip"); 6 7 Thread. currentThread. isBackground = true; 8 9 ThreadPool. queueUserWorkItem (o) => 10 {11 var t = Thread. currentThread. managedThreadId; 12 13 var result = CallContext. logicalGetData ("name"); 14 15 Console. writeLine ("I am a working thread: Name:" + result); 16 17}); 18 19 Console. read (); 20} 21}

 

It can be seen that the value set in the main thread has been read by the working thread. Is it very interesting? It provides another method for passing values between threads. We also saw that once IsFlowSuppressed

Then, the context returns null, which prevents the message of logicCallContext from being passed to the working thread. You can use ExecutionContext. SuppressFlow () to do so.

Take a look.

1 class Program 2 {3 static void Main (string [] args) 4 {5 CallContext. logicalSetData ("name", "ctrip"); 6 7 // block logical Data Flow 8 ExecutionContext. suppressFlow (); 9 10 Thread. currentThread. isBackground = true; 11 12 ThreadPool. queueUserWorkItem (o) => 13 {14 var t = Thread. currentThread. managedThreadId; 15 16 var result = CallContext. logicalGetData ("name"); 17 18 Console. writeLine ("I am a working thread: Name:" + result); 19 20}); 21 22 Console. read (); 23} 24}

 

Now the conclusion is that the context of the master thread requires a lot of code, so if the worker thread does not use the information of the master thread, you should disable the display.

It is of great benefit to the performance of working threads.

 


C # The QueueUserWorkItem method of the ThreadPool class cannot call a method with parameters?

Yes.
ThreadPool. queueUserWorkItem (new WaitCallback (obj => {sTime = DateTime. now; foreach (Node node in this. importNodes. where (p => p. TNode. nodeCode. substring (2, 1) + p. TNode. nodeCode. substring (7, 1) = "11" | p. TNode. nodeCode. substring (2, 1) + p. TNode. nodeCode. substring (7, 1) = "81 "). toList () {ThreadCount ++; UserTime = DateTime. now-sTime; new Thread (new ParameterizedThreadStart (CalculateTPath )). start (node); while (true) {CpuUser = Math. round (CpuWatch. nextValue (), 2); UserTime = DateTime. now-sTime; if (ThreadCount <MaxThreadCount) {break;} Thread. sleep (50);} // CpuUser = Math. round (CpuWatch. nextValue (), 2); // UserTime = DateTime. now-sTime ;...... remaining full text>

I have read the source code of Runnable, which contains only one abstract method.

MyRunnable runnable = new MyRunnable ("A thread"); // MyRunnable implements the Runnable interface
Thread demo = new Thread (runnable); // the object to be converted to a Thread
Demo. start ();

Below is a Thread constructor, that is, the constructor used in the second row above,
The received type is java. lang. Runnable, so you cannot customize it.
The runnable class is very simple.
Public Thread (Runnable target ){
Init (null, target, "Thread-" + nextThreadNum (), 0 );
}

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.