Java Attack c#--Syntax thread synchronization

Source: Internet
Author: User
Tags mutex volatile

In the previous chapter we talked about the application of C # thread orientation. But the author does not talk about another point of knowledge in multi-threading--synchronization. There is a possibility that dirty data can occur in multithreaded application development. The ability to synchronize is more or less used. This chapter will talk about thread synchronization issues. According to the author over the years. NET development can learn that there are at least four ways to synchronize. Such as. Lock, volatile, monitor and so on.

Lock mode

The keyword for lock is similar to the Java synchronized keyword. But there is a certain difference. The Java synchronized keyword may be modified above the method. Unfortunately, C # cannot be modified on the method. Is there any difference in usage? Why don't we take a look at the code?

C#:

Lock (aomilock) {    thread.sleep (300000);     I+ +;     Console.WriteLine (aomilock.name);}

The above aomilock is just an instance of the author-defined class. Obviously the author does not see how big the difference in the wording. For the use of lock, one of the newcomers asked me this: if I had two static global variables. A parameter value that is used to lock. That is the position of the above Aomilock. The other is inside lock. That is the curly braces inside. So can you change the value inside the lock somewhere else? I can only say sorry to him. can be modified.

Note: The above mentioned volatile keyword facts in Java also have the volatile keyword. are scoped to the variable level. The effect is just to make the change visible. This is what Java is like. Also, if you want to use the Synchronized keyword as a way to modify it. Sorry, please use [MethodImpl (methodimploptions.synchronized)].

Monitor class

The Monitor class is a bit like the Locak keyword in use. It's just that the monitor class itself provides too much flexible functionality. Does anyone know that a call lock interface is provided after Java 5.0. His instance class is Reentrantlock. His function is similar to the Monitor class.

BOOL false  ref  acquirelock);           // content i++; Console.WriteLine ("add i=" + i);         Monitor.Exit (aomilock);
Mutex class

This is a mutual exclusion lock, the author seldom use him to synchronize. The role of a mutex class can be between processes. So more is being used on a computer that can only run one application's functionality. And he's using a lot more resources. But I have no way to prove it. In short, I seldom use him on the right.

1  class Program2     {3          Public Staticmutex mutex;4         Static voidMain (string[] args)5         {6             BOOLcreated;7Mutex =NewMutex (false,"aomiapplication", outcreated);8 9 Console.readkey ();Ten  One         } A  -          Public Static voidAdd () -         { the              for(inti =0; I <Ten; i++) -             { - mutex. WaitOne (); -Console.WriteLine ("Add i="+i); + mutex. ReleaseMutex (); -  +             } A  at         } -}

The constructor of the mutex class The first parameter is used to represent. Whether to acquire mutex rights when creating a new mutex class. True indicates immediate availability. False words are obtained using the WaitOne method. I believe I do not have to say that we understand.

Semaphoreslim class

Semaphoreslim Class I think he is a class that controls the amount of thread. He is often used to control the number of threads or asynchronous runs that can run at most current applications. The author more used to design the company's framework when applied.

classProgram { Public StaticSemaphoreslim SS =NewSemaphoreslim (4); Static voidMain (string[] args) {             for(inti =0; I <Ten; i++) {thread thread=NewThread (ADD); Thread.            Start ();        } console.readkey (); }         Public Static voidAdd () {if(SS. Wait ( -) {Console.WriteLine ("running in progress"); Thread.Sleep ( -); Ss.            Release (); }            Else{Console.WriteLine ("Thread Busy"); }                }    }
AutoResetEvent class

I personally think this class does not belong to the synchronization class inside. More think he is a signal of a concept. But he can also realize the synchronization of small functions. I often use it in the design framework.

classProgram { Public StaticAutoResetEvent mainevent =NewAutoResetEvent (false); Static voidMain (string[] args) {Thread Thread=NewThread (Execute); Thread.            Start (); Mainevent.set ();//tell him he can do it.Console.readkey (); }         Public Static voidExecute () {mainevent.waitone (); Console.WriteLine ("Execute is running"); //content        }    }
This chapter summarizes

This chapter focuses on some common ways of synchronizing data between threads. Of course, the above is only used by the author. Not comprehensive. Okay, here's the chapter.

Java Attack c#--Syntax thread synchronization

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.