Getting started based on .NET-based multi-threaded programming ZZ

xiaoxiao2021-04-06  301

Introduction Multithreading is an important aspect that needs to focus on building large systems, especially when making a trade-off between efficiency (how fast the system is running?) Appropriate use of multi-threads can greatly improve system performance.

What is thread?

The programs that are running on the system are a process. Each process contains one to multiple threads. The process may also be the entire program or the dynamic execution of some of the program. The thread is a set of instructions, or the special segment of the program, which can be executed independently in the program. You can also understand it as a context of code running. Therefore, the thread is basically a lightweight process, which is responsible for performing multitasking in a single program. Usually

The operating system is responsible for scheduling and execution of multiple threads.

What is multi-thread?

Multi-threaded is to make multiple threads parallel to complete multiple tasks to improve system efficiency. The thread is implemented when the same time needs to complete a plurality of tasks.

There are the following benefits:

· Use threads to put the tasks in the program occupied in a long time to deal with the background

· The user interface can be more attractive, so, such as the user clicks on a button to trigger the processing of some events, you can pop up a progress bar to display the progress of the processing.

· The running speed of the program can speed up

· Things are more swimming in some waiting tasks, such as user input, file read and write and network transmission and reception data. In this case we can release some precious resources such as memory, and so on.

There are still many benefits of using multi-threaded, here is not explained.

Background of some thread models

We can focus on some models commonly used in the Win32 environment.

· Single-threaded model

In this thread model, there can only be one thread in a process, and the remaining process must wait for the current thread to complete. The disadvantage of this model is that the system has a small task must take a long time.

· Block Thread Model (Single Thread Multiple Model STA)

In this model, a program may contain multiple execution threads. Here, each thread is divided into a separate block in the process. Each process can contain multiple blocks that can share data in multiple blocks. The program specifies the execution time of the thread in each block. All requests pass

The Windows Message queue is serialized so that you can only access one block at each time, so there is only one separate process to be executed at a certain time. This model is the advantage of a single-threaded model that can respond to the tasks of the multiple user requests at the same time, not just a single user request. But its performance is not very good because it uses a serialized thread model, and the task is a pick one.

· Multi-threaded block model (free thread block model)

Multi-threaded block model (MTA) has only one block in each process instead of multiple blocks. This single block controls multiple threads instead of a single thread. There is no message queue here because all threads are part of the same block and can be shared. Such programs are blocks the execution speed of single-threaded models and STA, because the system's load is reduced, thus optimizing the time of system IDLE. These applications are generally complicated because the programmer must provide thread synchronization to ensure that the thread does not concurrently the same resource, resulting in competitiveness. There must be a lock mechanism here. But this may cause the system deadlock.

How does multi-thread work in .NET?

In essence and structures, .NET is a multi-threaded environment. There are two major multi-threaded methods to be .NET advocated: using ThreadStart to start your own process, direct (using threadpool.queueuserworkItem) or indirect (such as Stream.BeginRead, or calling beginInvoke) using the ThreadPool class. In general, you can "manually" create a new thread for a long time, and those who are running in a short-running task, especially those that often need to begin, and the process pool is a very good choice. Process pools can run multiple tasks at the same time, and you can use the framework class. For information on resource is required, it can limit only one thread to access resources at a certain moment. This situation can be considered to achieve a lock mechanism to thread. The base class of the thread is System.Threading. All threads are managed by CLI. · Create thread:

Create an instance of a new THREAD object. Thread's constructor accepts a parameter:

Thread Dummythread = New ThreadStart (DummyFunction)); 0000-00-00 DUMMYTART (DUMMYFUNCTION);

· Execute thread:

Run the thread using the Start method in the Thieading namespace:

Dummythread.start ();

· Combined thread:

There is often a need to combine multiple threads, that is, when a thread requires the end of another thread to complete its own task. Suppose DummyThread must wait for DummyPrioritythread to complete your own task, we only need to do this:

DummyPrioritythread.join ();

· Pause thread:

Make threads suspending a given second

DummyPrioritythread.sleep (

· Survanting thread:

If you need to abort the thread, you can use the following code:

DummyPriorityThread.abort ();

·Synchronize

Often we will encounter cases that need to be synchronized between threads, and the following code gives some methods:

using System; using System.Threading; namespace SynchronizationThreadsExample {class SynchronizationThreadsExample {private int counter = 0; static void Main () {SynchronizationThreadsExample STE = new SynchronizationThreadsExample (); STE.ThreadFunction ();} public void ThreadFunction () {Thread DummyThread = new Thread (new ThreadStart (SomeFunction); DummyThread.IsBackground = true; DummyThread.Name = "First Thread"; DummyThread.Start (); Console.WriteLine ( "Started thread {0}", DummyThread.Name); Thread DummyPriorityThread = new Thread (new ThreadStart (SomeFunction)); DummyPriorityThread.IsBackground = true; DummyPriorityThread.Name = "Second Thread"; DummyPriorityThread.Start (); Console.WriteLine ( "Started thread {0}", DummyPriorityThread.Name); DummyThread. Join (); DummyPrioritythread.join ();} public void somfunction () {trei {whele (counter <10) {int TempCounter = Counter; TempCounter ; thread.sleep (1); C ounter = tempCounter; Console.WriteLine ( "Thread {0} SomeFunction:. {1}", Thread.CurrentThread.Name, counter);}} catch (ThreadInterruptedException Ex) {Console.WriteLine ( "Exception in thread {0}" Thread.currentthread.Name);} finally {console.writeline ("Thread {0} EXITING.", Thread.currentthread.name);}}}} · Using Interlock

C # provides a special class called interlocked, providing the implementation of the lock mechanism, we can join the following code to implement the lock mechanism:

Interlocked.somefunction (Ref counter);

· Use lock

This is to lock the code critical area for synchronization, the lock code is as follows:

Lock (this) {some statements;}

· Using Monitor

We can use when there is a need to perform thread management:

Monitor.enter (this);

Others also have some ways to manage, here is not mentioned. Disadvantages of thread

The thread naturally has a shortcoming, and some of the following:

• If there is a lot of threads, it will affect performance because the operating system needs to switch between them;

· More threads need more memory space

· The thread will bring more bugs to the program, so be careful

· Threading stops need to consider its impact on program operation

· Usually block model data is shared in multiple threads, requiring a suitable lock system to replace data sharing

转载请注明原文地址:https://www.9cbs.com/read-132378.html

New Post(0)