NET multi-thread exploration-mutex lock, semaphores, and events (performances of xiaoxinhe and the demolition force)

Source: Internet
Author: User
Tags net thread

Mutex lock-inaccurate clock

Concepts:
A mutex lock is a mutex synchronization object, which can be obtained by only one thread at a time.
In the previous article, we used Mutex to implement the clock program.
Class Program
{
Static void Main (string [] args)
{
Clock C = new Clock ();
C. RunClock (1 );
Console. Read ();
}
}
Public class Clock
{
Public Mutex CTX = new Mutex ();

// Start running the clock and enter the running minute
Public void RunClock (Int32 Minute)
{
Thread T1 = new Thread (object Minute1) =>
{
Int32 m = Convert. ToInt32 (Minute1) * 60/2;
While (m> 0)
{
DI (true );
M --;
}
});
Thread T2 = new Thread (object Minute1) =>
{
Int32 m = Convert. ToInt32 (Minute1) * 60/2;
While (m> 0)
{
DA (true );
M --;
}
});
T1.Start (true );
T2.Start (true );
}

Public void DI (bool run)
{
CTX. WaitOne ();
If (! Run)
{
CTX. ReleaseMutex ();
Return;
}
Else
{
Console. WriteLine ("succeeded ");
Thread. Sleep (1000 );
CTX. ReleaseMutex ();
}
}

Public void DA (bool run)
{
CTX. WaitOne ();
If (! Run)
{
CTX. ReleaseMutex ();
Return;
}
Else
{
Console. WriteLine (" ");
Thread. Sleep (1000 );
CTX. ReleaseMutex ();
}
}
}



 

Why? Everything seems reasonable!

Here I will only express my understanding. I also ask a garden friend to carefully analyze it. After all, my personal understanding may be wrong!
If you find that I understand it wrong, please comment out in the comments that I will learn more soon!

The Monitor clock is locked by lock, and the lock will be compiled into the Monitor's Enter and Exit.
The key point is that when the Monitor is in the Pulse (obj), it has determined that another thread waiting for the obj to be released has the execution right!
After the ReleaseMutex lock is released, the current thread and other waiting threads execute WaitOne, leading to the competition for thread execution right!
As the program runs, the competition between threads is fierce.
Mutex lock-release of the cup


The following uses mutex lock to implement an example. A bomb can only be split by one person. If more than one person exists, it will explode.
Class Program
{
Static void Main (string [] args)
{
Bomb B = new bomb ();
B. Disassemble ();
B. Disassemble ();
Console. Read ();
}
}
Public class bomb
{
Private Int32 heat = 0;
Public Mutex m = new Mutex ();

Public void ()
{
Thread t = new Thread (inside the bomb );
T. Start ();
}

Private void bomb internal ()
{
M. WaitOne ();
Heat ++;
Thread. Sleep (1000 );
If (heat> 1)
{
Console. WriteLine ("bomb explosion! Refer to Marx for release ...");
M. ReleaseMutex ();
Return;
}
Popularity --;
Console. WriteLine ("bomb security removal! The bonus of the sharding operator is doubled this month ...");
M. ReleaseMutex ();
}
}




Fortunately, the bonus this month has been doubled. If Mutex is removed, Marx will wait for them to chat.
Semaphores-Semaphore

The mutex lock and synchronization both lock a resource and allow only one thread to operate.
The mutex lock is not suitable for cases where a limited number of threads can be allowed. Here, a semaphore is required.
Semaphores use a counter to control access to shared resources. If the number of idle Counters is greater than 0, access is allowed. If it is equal to 0, access is denied.
 

Public Semaphore (int initialCount, int maximumCount );

InitialCount: the number of initial requests that can be granted to semaphores at the same time.
MaximumCount: Maximum number of requests that can be simultaneously granted to semaphores.
 

Public virtual bool WaitOne ();
Public int Release ();

WaitOne (): Stop the current thread until the current System. Threading. WaitHandle receives the signal.
Release (): exit the semaphore and return the previous count.

Next, let's take a drop-down ticket to demonstrate it.
 

Class Program
{
Static void Main (string [] args)
{
// The bricklayer of the relevant department is called the beast to tell the bomb to be split by up to four people at the same time
Int32 = 4;
Bomb B = new bomb (number of people who have released the bomb );
While (number of people who have opened the shell> 0)
{
B. Disassemble ();
Number of people who have opened the bullet --;
}
Console. Read ();
}
}
Public class bomb www.2cto.com
{
Private Int32 maximum temperature = 0;
Private Int32 heat = 0;
Private Semaphore S;
 
Public bomb (Int32 limit)
{
Maximum temperature = 3;
S = new Semaphore (limit, limit );
}
 
Public void ()
{
Thread t = new Thread (inside the bomb );
T. Start ();
}
 
Private void bomb internal ()
{
S. WaitOne ();
Heat ++;
Thread. Sleep (1000 );
If (heat> maximum temperature)
{
Console. WriteLine ("bomb explosion! Refer to Marx for release ...");
S. Release ();
Return;
}
Popularity --;
Console. WriteLine ("bomb security removal! The bonus of the sharding operator is doubled this month ...");
S. Release ();
}
}

 

 


The bullet breaker of the Cup. Here, the barrier is called a beast. The error indicates a maximum of four people, and the bomb supports a maximum of three people! Alas...
 
 

 

Implement with events-happy little new

An event is another synchronization object. ManualResetEvent and autoreseteventare both classes that implement the event synchronization function and are derived from the EventWaitHandle class.

This section describes ManualResetEvent.
Public ManualResetEvent (bool initialState );
Public virtual bool WaitOne ();
Public bool Reset ();
Public bool Set ();

The first is the constructor. The input variable is whether the event signals.
The second is to wait for an event to signal, during which it is blocked.
The third is to reset the event to the status where no signal is sent.
The last one is to set the event to the sending signal status.

The main implementations of ManualResetEvent and AutoResetEvent are the same. The only difference is that ManualResetEvent needs to be manually set to unsent, while AutoResetEvent is automatically set.

A day with the help of novogene
Class Program
{
Static void Main (string [] args)
{
ManualResetEvent mal = new ManualResetEvent (false );
Beauty sister beauty = new beauty sister ();
Small new help = new small new ();
Thread t1 = new Thread (new ParameterizedThreadStart (beauty. Beautiful girl and sister going to the streets ));
Thread t2 = new Thread (new ParameterizedThreadStart (new helper. Small new dispatch ));
T1.Start (mal );
T2.Start (mal );
Console. Read ();
}

Public class beauty sister
{
Public void beauty sister (object Mal)
{
Thread. Sleep (2000 );
Console. WriteLine ("the beautiful young girl and sister are on the streets ...");
Thread. Sleep (1000 );
(ManualResetEvent) Mal). Set ();
}
}

Public class
{
Public xiaoxin ()
{
Thread. Sleep (1000 );
Console. WriteLine ("xiaoxin holds milk tea and hides it in the green belt on the street ...");
Thread. Sleep (1000 );
}

Public void (object Mal)
{
ManualResetEvent Mal1 = (ManualResetEvent) Mal;
Console. WriteLine ("looking for beautiful girl and sister xiaoxin ...");
// Wait for the appearance of the beauty sister
Mal1.WaitOne ();
Console. WriteLine ("xiaoxin ran to the front of her sister, took off her pants, lit up the elephant, and started to dance the elephant ...");
Console. WriteLine ("ass twisting," elephant, elephant, elephant ..."");
Mal1.Reset ();
}
}
}

 

 



No...
 

 

To sum up!

After writing so much, you should think about these Synchronization Methods. Although the idea is the same! But they have their own characteristics.
When you are free, let's take a look at the core part of the thread in CLR 3, which clearly explains the principles of these synchronization.
In short, the thread water is too deep. Let's walk slowly. Next I will talk about some of the remaining Thread Synchronization Methods, and then I will summarize the NET thread synchronization at the end.

 

Author: Sea is not blue
 
 

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.