A preliminary study on the multithreading mechanism of C # (1)

Source: Internet
Author: User

A preliminary study on the multithreading mechanism of C # (1)

Note: All the code in this article is run in the. net Framework RC3 environment through

I. multithreading Concept

Windows is a multitasking system. If you are using windows 2000 or later, you can view the programs and processes running on the current system through the task manager. What is a process? When a program starts to run, it is a process that refers to the memory and system resources used by the running programs and programs. A process is composed of multiple threads. A thread is an execution stream in a program, and each thread has its own proprietary register (Stack pointer, program counter, etc ), but the code zone is shared, that is, different threads can execute the same function. Multithreading means that a program contains multiple execution streams, that is, a program can run multiple different threads to execute different tasks at the same time, that is to say, a single program is allowed to create multiple parallel threads to complete their respective tasks. A browser is a good example of multithreading. In a browser, you can scroll the page while downloading a JAVA application or image, and play animations and sounds when accessing a new page, print files.

The advantage of Multithreading is that it can improve the CPU utilization. Any programmer does not want his or her program to work normally. In a multithreaded program, a thread must wait, the CPU can run other threads instead of waiting, which greatly improves the program efficiency.

However, we must also recognize the negative aspects that the thread itself may affect system performance to use the thread correctly:

The thread is also a program, so the thread needs to occupy the memory. The more threads occupy the memory, the more
Multithreading requires coordination and management, so it requires CPU time to track threads.
Inter-thread access to shared resources will affect each other, and the problem of competing to share resources must be solved.
Too many threads will lead to complicated control, and may eventually cause many bugs.

Based on the above understanding, we can use a metaphor to deepen our understanding. Suppose there is a company with many employees with their respective duties, then we can think that this normal operating company is a process, and the staff in the company is a thread. A company must have at least one employee. Similarly, a process must contain at least one thread. In a company, you can do everything for one employee, but the efficiency is obviously not high. A company cannot do anything bigger. In a program, you can use only one thread to do things, in fact, this is true for outdated languages such as fortune and basic, but like a company, it is very inefficient. If it is a large program, it is less efficient-in fact, there is almost no single-threaded commercial software. The more employees the company has, the more salaries the boss has to give to them, and it has to spend a lot of energy to manage them and coordinate the contradictions and interests between them. The same is true for the program, the more threads consume more resources, the CPU time is required to track the threads, and problems such as deadlocks and synchronization must be solved. In short, if you don't want your company to be called a "bag company", you will have a few more employees. If you don't want your program to look childish, introduce multithreading in your program!

This article will discuss the multithreading mechanism in C # programming and solve the thread control and multi-thread communication issues through some examples. In order to save the tedious steps for creating a GUI and more clearly approach the essence of the thread, all the following programs are Console programs and the final Console of the program. readLine () is used to stop the program midway through, so that you can see the output in the execution process clearly.

Okay, let's try out the multi-threaded C!

2. manipulate a thread

When any program is executed, there must be at least one main thread. The following small program can give readers an intuitive impression:

[CODE]
File: // SystemThread. cs
Using System;
Using System. Threading;

Namespace ThreadTest
{
Class RunIt
{
[STAThread]
Static void Main (string [] args)
{
Thread. CurrentThread. Name = "System Thread"; // Name the current Thread "System Thread"
Console. WriteLine (Thread. CurrentThread. Name + "Status:" + Thread. CurrentThread. ThreadState );
Console. ReadLine ();
}
}
}
[/CODE]

What do you see after compilation and execution? Yes, the program will generate the following output:

System Threads Status: Running

Here, we get the Thread currently being executed through the static attribute CurrentThread of the Thread class, assign the value "System Thread" to its Name attribute, and finally output its current state (ThreadState ). The so-called static attribute is the public attribute of all objects in the class. No matter how many instances of the class you have created, the static attribute of the class has only one in the memory. It is easy to understand why CurrentThread is static-although multiple threads exist at the same time, the CPU can only execute one of them at a certain time point.

As demonstrated by the above program, we use the Thread class to create and control threads. Note that the program header uses the following namespace:

The following is the program code:

Using System;
Using System. Threading;


In. net framework class library, all classes related to multithreading applications are stored in the System. Threading namespace. The Thread class is used to create threads, and the ThreadPool class is used to manage Thread pools. In addition, it provides a mechanism to solve actual problems such as Thread execution arrangements, deadlocks, and inter-Thread communication. If you want to use multithreading in your application, you must include this class. The Thread class has several important methods, which are described as follows:

Start (): Start the thread
Sleep (int): a static method that pauses the specified number of milliseconds of the current thread.
Abort (): This method is usually used to terminate a thread.
Suspend (): This method does not terminate the unfinished thread. It only suspends the thread and can be recovered later.
Resume (): resumes the execution of threads suspended by the Suspend () method.

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.