157 recommendations for writing high-quality code to improve C # programs--Recommendation 75: Beware of threads not starting immediately

Source: Internet
Author: User

Recommendation 75: Beware that threads do not start immediately

Most modern operating systems are not a real-time operating system, as is the case with Windows systems. Therefore, we cannot expect our thread to start immediately. Windows internally implements a special algorithm for scheduling between threads, and at a specific time it determines which thread should be running. This is reflected at the bottom of a thread that is allocated a certain amount of CPU time and can be used to perform a small piece of work (because the allocated CPU time is very short, so even if thousands of threads are running in the operating system, we feel that the applications are executing concurrently). Windows chooses how the next segment of CPU time will be dispatched at the appropriate time according to its own algorithm.

Thread scheduling is a complex process, and for C # developers it is important to understand that scheduling between threads takes a certain amount of time and space overhead, and that it is not real-time. The following is an example of a test that was meant to pass 0 to 9 to 10 different threads, but the result backfired:

Static int_id =0; Static voidMain () { for(inti =0; I <Ten; i++, _id++) {Thread T=NewThread (() ={Console.WriteLine (string. Format ("{0}:{1}", Thread.CurrentThread.Name, _id));          }); T.name=string. Format ("thread{0}", i); T.isbackground=true;      T.start ();  } console.readline (); } 

The possible output of the above code is:
Thread0:2
Thread4:5
Thread2:3
Thread1:3
Thread5:5
Thread6:6
Thread7:7
Thread8:9
Thread3:3
Thread9:10
The output of this code confirms from two aspects that the thread is not started immediately.

First, we see that the threads are not started in sequence. In the code logic, the thread that precedes start may be executed later than the one on the back start.

Second, the ID value inside the incoming thread is no longer the current ID value in the For loop execution. Take Thread9 for example, in the For loop, its current value is 9, and Thread9 really get executed, the ID has jumped out of the loop, has already become 10.

In order for the requirements to be correctly encoded, the above for loop needs to be modified into a synchronous code:

Static int_id =0; Static voidMain () { for(inti =0; I <Ten; i++, _id++) {NewMethod1 (I, _id);      } console.readline (); }       Private Static voidNEWMETHOD1 (intIintRealtimeid) {Thread T=NewThread (() ={Console.WriteLine (string. Format ("{0}:{1}", Thread.CurrentThread.Name, Realtimeid));          }); T.name=string. Format ("thread{0}", i); T.isbackground=true;      T.start (); }  } 

The above code output:
thread0:0
Thread3:3
Thread1:1
Thread2:2
Thread5:5
Thread4:4
Thread6:6
Thread7:7
Thread8:8
Thread9:9
As you can see, although the thread maintains a feature that does not start immediately, the ID value of the incoming thread can be passed in correctly because it becomes the synchronization code inside the For loop.

Turn from: 157 recommendations for writing high-quality code to improve C # programs Minjia

157 recommendations for writing high-quality code to improve C # programs--Recommendation 75: Beware of threads not starting immediately

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.