Multi-thread (I) and multi-thread (

Source: Internet
Author: User

Multi-thread (I) and multi-thread (

Hey, you guys.

I haven't seen you for a long time. I have recently been busy learning English and dealing with some chores, so I haven't had time to update my blog. The company is currently not active and relatively idle. So, I have time to study <knocking on the door of C #>. It is said that the author is a 40-year-old junior high school mathematics teacher, self-study C #. Self-taught programming by people in their 40 s is admirable. This book describes the basic knowledge of C # language. The author explained it clearly and benefited a lot after reading it. Many people have been familiar with the basic principles, and even do not understand the basic principles at all. As Confucius said: "the day of death is just like the night ." This book is really helpful for beginners. NET programmers. Now, let's start learning today.

Multithreading is a deep Technology in. NET. Today, let's learn more about multithreading.

Thread Concept

When using computers, you can listen to music, download movies, and browse the Web page. How does a computer meet the user's needs? In the original operation, three applications will be created to perform user operations through the application. Each application is considered as a continuous instruction stream, and the CPU executes these Instruction Streams one by one. However, the CPU of earlier computers does not allow multiple command streams to be executed at the same time. How does the computer do this? The operating system also creates three processes while creating three applications ). Processes not only include the application's command flow, but also the memory and registers required to run the application. The operating system executes applications through processes. We can regard processes as execution routes. The operating system uses "time slice rotation" to execute these processes in turn. Therefore, the process is executed concurrently at a macro level, which is also executed at a micro level. That is to say, the computer does not support listening to music, downloading movies, or Browsing webpages at the same time. The CPU is executed in turn, but the switching time is short and we cannot feel it. In this scenario, when a webpage plays Flash, there is a text box on the webpage to accept user input. This webpage needs to play Flash while accepting user input. Note (in my personal understanding, the CPU executes the web page's process commands, and the process also needs to play Flash and receive user input commands ). In the past, we would need a complicated piece of code to implement this requirement. However, the emergence of Multi-Threading technology can easily achieve this requirement. You can create two threads in the web page process. These two threads are used to play Flash and accept user input. We can regard multiple threads in the process as multiple execution routes. Multiple Threads in a process share resources. Therefore, switching between threads is much faster than switching between processes. We can regard the thread as a lightweight process (LightweightProcess ). The operating system uses scheduling programs to manage threads without the concern of programmers. We only need to write the threads, which are the basic unit of CPU scheduling.

Thread class

When a computer runs an application, a process is created, and multiple threads are created for the process to execute the Work. We call the Thread that executes some Work as the Work Thread ). In C #, Thread processing is completed through the Thread class in the System. Threading namespace.

Using System. Threading; // do not forget to add reference // declare the code of a Thread workThread = new Thread (entryPoint );

EntryPoint: indicates the entry method. The thread executes the code from the first line of the entry method. We can see that the parameter type of the constructor of the Thread class is a delegate type. That is to say, the return value and parameters of the entryPoint function are determined by the delegate parameters of the constructor of the Thread class.

// The delegate type of the constructor parameter of the Thread class public delegate void ThreadStart (); public delegate void ParameterizedThreadStart (object obj );

The entry method must be a thread start or ParameterizedThreadStart delegate.

To sum up, it takes two steps to create a thread.

// Step 1 create the entry method private void EntryPoint () {// code of the thread ......................} // Step 2: Create the Thread object Thread workThread = new Thread (EntryPoint );

 

Thread priority

We have to deal with many things in our work and life. In general, when the matter is tight, it should be handled in a timely manner. Otherwise, it should be handled later. The same is true for thread processing commands. Set the Priority of a Thread through the Priority attribute of the Thread class. The Priority attribute is a ThreadPriority enumeration. This enumeration has the following five priority levels:

Normal, AboveNormal, Highest, BelowNormal, and Lowest.

Run the program to test the thread priority:

// WorkThread1 Thread workThread1 = new Thread (delegate () {for (int I = 0; I <100000000; I ++) {if (I % 1000000 = 0) {Console. write ("A") ;}}); // workThread2 Thread workThread2 = new Thread (delegate () {for (int I = 0; I <100000000; I ++) {if (I % 1000000 = 0) {Console. write ("B") ;}}); // start thread workThread1.Start (); workThread2.Start ();

Run the program. The effect is as follows:

// WorkThread1 Thread workThread1 = new Thread (delegate () {for (int I = 0; I <= 500000000; I ++) {if (I % 1000000 = 0) {Console. write ('A') ;}}); // workThread2 Thread workThread2 = new Thread (delegate () {for (int I = 0; I <= 500000000; I ++) {if (I % 1000000 = 0) {Console. write ('B') ;}}); // modify the Thread priority workThread1.Priority = ThreadPriority. aboveNormal; workThread2.Priority = ThreadPriority. belowNormal; // start thread workThread1.Start (); workThread2.Start (); // main thread code for (int I = 0; I <= 500000000; I ++) {if (I % 1000000 = 0) {Console. write ('M ');}}

 

In fact, besides workThread1 and workThread2, there is also a Main Thread ). We modified the code of the main thread to observe how the three threads work across each other. In our code, the Priority attribute of workThread is set to higher than normal (AboveNormal), and the Priority attribute of workThread2 is set to lower than normal (BelowNormal ). At this time, the effect of running the program is as follows:

Static void Main (string [] args) {// workThread1 Thread workThread1 = new Thread (delegate () {for (int I = 0; I <= 500000000; I ++) {if (I % 1000000 = 0) {Console. write ('A') ;}}); // workThread2 Thread workThread2 = new Thread (delegate () {for (int I = 0; I <= 50000000; I ++) {if (I % 1000000 = 0) {Console. write ('B') ;}} workThread1.Join (); for (int I = 0; I <= 50000000; I ++) {if (I % 10000 = 0) {Console. write ('B') ;}}); // start thread workThread1.Start (); workThread2.Start ();}

We call the join () method of workThread1 in the thread workThread2 entry method. When the program executes the join () method, workThread2 stops working and executes workThread1, workThread2 is executed only after workThread1 is executed. The program running result is as follows:

The Join () method can also accept a parameter that represents milliseconds. When this time is reached, it will exit regardless of whether the execution is complete or not.

Thread status

There are 7 states in a thread, including UnStarted, Running, WaitSleepJoin, and SuspendRequested), the pending status (sucanceled DED), the aborting Request status (AbortRequested), and The Stopped status ). You can refer to the following picture to learn about the status in these 7 states:

1. Unstarted)

When a thread is created, its status changes to UnStarted ).

2. Running status (Running)

When the thread calls the Start () method, the thread state changes to the running state (Ruuning ).

3. Waiting for sleep insertion (WaitSleepJoin)

When running threads call Methods Sleep (), Join (), or Wait (), the thread status changes to waiting for Sleep insertion (WaitSleepJoin ). at this time, if the Pulse () or Interrupt () thread is called, The status will change to Running.

4. Suspend the Request body (SuspendRequested)

When the running state thread calls the method Suspend (), the thread status changes to SuspendRequested.

5. Suspended status)

When the Suspend () method is called, the thread is not immediately suspended, but in the SuspendRequested state. The thread executes several more commands. When the thread is in a safe state, the thread is Suspended, and the thread status changes to suincluded. Call the Resume () method to change the thread-like body to the Running state.

6. Abort Request status (AbortRequested)

When a running thread calls method Abort (), the thread status changes to AbortRequested.

7. Abort (Aborted)

When a thread calls the Abort () method, the thread will not immediately stop, but will be in the AbortRequested state, and then execute several commands. When the thread is in a safe state, the thread will be aborted, the thread status changes to Stopped.


Multi-thread upload Concept

Yes. I used to write FTP uploads. It is done with multiple threads.

In C language?

I would like to recommend some good tutorials for you. You may need to use: C ++ Builder multi-thread programming technology: www.it55.com/...5.html to compile multi-thread program instances with MFC: the web server program (multithreading) Written in www.it55.com/..7.html C ++ is a multi-threaded instance tutorial.

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.