Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to realize. Net object-oriented multithreading and multithreading advanced

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article focuses on "how to achieve. Net object-oriented multi-threading and multi-threaded advanced", interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Next let the editor to take you to learn "how to achieve. Net object-oriented multithreading and multithreading advanced"!

The solution of thread safety and thread conflict in thread resource sharing in. Net object-oriented programming phase; multi-thread synchronization, thread synchronization using thread lock and thread notification, the specific content is as follows:

1. ThreadStatic characteristics

Properties: [ThreadStatic]

Function: specify that static fields have different values in different threads

Before that, let's look at an example of multithreading:

We define a static field:

Static int num = 0

Then create two threads to accumulate separately:

New Thread (() = > {for (int I = 0; I)

< 1000000; i++) ++num; Console.WriteLine("来自{0}:{1}", Thread.CurrentThread.Name, num);}){ Name = "线程一" }.Start(); new Thread(() =>

{for (int I = 0; I)

< 2000000; i++) ++num; Console.WriteLine("来自{0}:{1}", Thread.CurrentThread.Name, num);}){ Name = "线程二" }.Start(); 运行多次结果如下:

As you can see, the results of the three runs are different, and this problem is caused by the problem of synchronization and sharing in multiple threads, that is, multiple threads share a resource at the same time. The easiest way to solve the above problem is to use the ThreadStatic feature of static fields.

When defining static fields, add the [ThreadStatic] attribute as follows:

The copy code is as follows:

[ThreadStatic]

Static int num = 0

Run it again with the same two threads, and the result is as follows:

No matter how many times it is run, the result is the same, and when the field is modified by the ThreadStatic feature, its value is different in each thread, that is, each thread reallocates memory space to the static field, of course, in a new operation, so that the problems caused by the static field are eliminated.

two。 Resource sharing

Multi-thread resource sharing, that is, multi-thread synchronization (resource synchronization), it should be noted that thread synchronization refers to the synchronization of the resources accessed by the thread, not the synchronization of the thread itself.

In the process of actually using multithreading, not all threads access different resources.

Let's look at an example of a thread. if we don't know how long it will take for the thread to complete, we wait for a fixed time (if 500 milliseconds):

Define a static field first:

Static int result

Create a thread:

Thread myThread = new Thread (() = > {Thread.Sleep (1000); result = 100;}); myThread.Start (); Thread.Sleep (500); Console.WriteLine (result)

The running results are as follows:

We can see that the result is 0, which is obviously not what we want, but often in the process of thread execution, we don't know how long it will take to complete. Can we have a notification after the thread finishes?

There are a lot of stupid ways, such as we might think of using a loop to detect thread state, which is not ideal.

.net provides us with a Join method, that is, thread blocking, which can solve the above problem. We use Stopwatch to time.

The improved thread code is as follows:

System.Diagnostics.Stopwatch watch = System.Diagnostics.Stopwatch.StartNew (); Thread myThread = new Thread (() = > {Thread.Sleep (1000); result = 100;}); myThread.Start (); Thread.Sleep (500); myThread.Join (); Console.WriteLine (watch.ElapsedMilliseconds); Console.WriteLine (result)

The running results are as follows:

The result is consistent with what we want.

3. Thread lock

In addition to the method in the above example, for thread synchronization, .NET also provides us with a locking mechanism to solve synchronization. The example above is improved again as follows:

First define a static field to store the lock:

Static object locker = new object ()

Here we don't have to think about what the object is. Continue to look at the improved thread:

System.Diagnostics.Stopwatch watch = System.Diagnostics.Stopwatch.StartNew (); Thread T1 = new Thread (() = > {lock (locker) {Thread.Sleep (1000); result = 100;}}); t1.Start (); Thread.Sleep (100); lock (locker) {Console.WriteLine ("thread time:" + watch.ElapsedMilliseconds); Console.WriteLine ("thread output:" + result);}

The running results are as follows:

The result is the same as the example above, and if the threading process is complex, you can see a significant reduction in time-consuming, which is a more efficient way to accomplish thread synchronization than blocking.

4. Thread notification

Earlier, I talked about whether it is possible to notify the waiting thread after a thread is finished. Net provides us with an event notification method to solve this problem.

4.1 AutoResetEvent

Define a notification object first

The copy code is as follows:

Static EventWaitHandle tellMe = new AutoResetEvent (false)

Improvements to the above thread are as follows:

System.Diagnostics.Stopwatch watch = System.Diagnostics.Stopwatch.StartNew (); Thread myThread = new Thread (() = > {Thread.Sleep (1000); result = 100; tellMe.Set ();}); myThread.Start (); tellMe.WaitOne (); Console.WriteLine ("thread time:" + watch.ElapsedMilliseconds); Console.WriteLine ("thread output:" + result)

The running results are as follows:

4.2 ManualResetEvent

There is also a ManualResetEvent manual mode as opposed to AutoResetEvent, and the difference between them is that ManualResetEvent is still passable after the end of the thread unless manual Reset is turned off. Let's look at an example:

First define an object for manual notification:

Static EventWaitHandle mre = new ManualResetEvent (false)

Create a thread:

System.Diagnostics.Stopwatch watch = System.Diagnostics.Stopwatch.StartNew (); Thread myThreadFirst = new Thread (() = > {Thread.Sleep (1000); result = 100; mre.Set ();}) {Name= "thread one"}; Thread myThreadSecond = new Thread () = > {mre.WaitOne (); Console.WriteLine (Thread.CurrentThread.Name + "get results:" + result + "(" + System.DateTime.Now.ToString () + ");}) {Name=" thread two "}; myThreadFirst.Start () MyThreadSecond.Start (); mre.WaitOne (); Console.WriteLine ("Thread time: + watch.ElapsedMilliseconds +" ("+ System.DateTime.Now.ToString () +"); Console.WriteLine ("Thread output:" + result + "(" + System.DateTime.Now.ToString () + ")")

The running results are as follows:

4.3. Semaphore

Semaphore is also a kind of thread notification. In the above notification mode, when a large number of threads are opened and closed using Reset (), if you do not use Sleep to sleep for a while, it is very likely that some threads will shut down in advance if some threads do not resume. For this unpredictable situation, .NET provides a more advanced notification method, Semaphore, to ensure that the above problems will not occur in super-multithreading.

First define a static field of the notification object:

The copy code is as follows:

Static Semaphore sem = new Semaphore (2,2)

Use a loop to create 100 threads:

For (int I = 1; I {sem.WaitOne (); Thread.Sleep (30); Console.WriteLine (Thread.CurrentThread.Name+ "" + DateTime.Now.ToString ()); sem.Release ();}) {Name= "thread" + I} .start ();}

The running results are as follows:

You can see the complete output of the results we want to see.

At this point, I believe you have a deeper understanding of "how to achieve. Net object-oriented multi-threading and multi-threading". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report