5 days no longer afraid of multithreading-4 days semaphore

Source: Internet
Author: User

Today, I have sorted out the related knowledge about semaphores. In fact, it is quite interesting to think about it. The lock and mutex can all implement thread synchronization. There are three main types of semaphores in the framework.

<1>: manualresetevent

<2>: autoresetevent

<3>: semaphore

 

Well, let's take a look at the usage of these things.

 

I. manualresetevent

This object has two semaphore states: true and false. If you are curious, you must know the difference between true and false. For more information, see the example below. There are three methods worth learning.

1: waitone

This method is used to block threads. By default, it is an indefinite blocking. Sometimes we don't want to do this. Instead, we adopt the timeout blocking method. If the timeout occurs, the blocking will be abandoned. This avoids the indefinite period.

Wait awkwardly.

2: Set

Manually change the semaphores to true, that is, resume thread execution.

3: reset

Manually change the semaphores to false to suspend thread execution.

 

Well, the following is an example.

 

<1> when the semaphore is set to false, waitone blocks indefinitely, and interaction between threads can be found.

 1   Public   Class Example
2 {
3 Public Static Void Main ()
4 {
5 Thread t = New Thread (run );
6
7 T. Name = " Jack " ;
8
9 Console. writeline ( " Current Time: {0} {1} {1}. I am the main thread. Please answer. " , Datetime. Now, T. Name );
10
11 T. Start ();
12
13 Thread. Sleep ( 5000 );
14
15 Mr. Set ();
16
17 Console. Read ();
18 }
19
20 Static Manualresetevent mr = New Manualresetevent ( False );
21
22 Static Void Run ()
23 {
24 Mr. waitone ();
25
26 Console. writeline ( " \ N current time: {0} main thread, main thread, {1} received! " , Datetime. Now, thread. currentthread. Name );
27 }
28 }

 

<2> when the semaphore is set to true, waitone blocks indefinitely. The experiment shows that waitone is not blocked.

 
 StaticManualresetevent mr =NewManualresetevent (True);

 

<3> the initial semaphore value is false. waitone times out for 2 S. Although the master thread has to wait for 5S to perform the set operation, waitone cannot wait until it is executed in advance.

 1   Public   Class Example
2 {
3 Public Static Void Main ()
4 {
5 Thread t = New Thread (run );
6
7 T. Name = " Jack " ;
8
9 Console. writeline ( " Current Time: {0} {1} {1}. I am the main thread. Please answer. " , Datetime. Now, T. Name );
10
11 T. Start ();
12
13 Thread. Sleep ( 5000 );
14
15 Mr. Set ();
16
17 Console. Read ();
18 }
19
20 Static Manualresetevent mr = New Manualresetevent ( False );
21
22 Static Void Run ()
23 {
24 Mr. waitone (2000 );
25
26 Console. writeline ( " \ N current time: {0} main thread, main thread, {1} received! " , Datetime. Now, thread. currentthread. Name );
27 }
28 }

Ii. autoresetevent

In vs Object Browser, we found that autoresetevent and manualresetevent both inherit from eventwaithandle, so the basic functions are the same, but it is worth noting that

One difference is that waitone will change the semaphore value. For example, if the initial semaphore is true, the waitone timeout semaphore will automatically become false, but manualresetevent will not.

 1   Public   Class Example
2 {
3 Public Static Void Main ()
4 {
5 Thread t = New Thread (run );
6
7 T. Name = " Jack " ;
8
9 T. Start ();
10
11 Console. Read ();
12 }
13
14 Static Autoresetevent AR =New Autoresetevent ( True );
15
16 Static Void Run ()
17 {
18 VaR State = ar. waitone ( 1000 , True );
19
20 Console. writeline ( " My current semaphore status: {0} " , State );
21
22 State = ar. waitone ( 1000 , True );
23
24 Console. writeline ( " I hate you, ignore me, your current status is: {0} " , State );
25
26 }
27 }

 

Iii. semaphore

This is newly added to. Net 4.0 to control the number of threads. The default constructor is initialcount and maximumcount, indicating the number of semaphores and

The maximum number of semaphores. In fact, the counter is used to allocate semaphores. When you waitone, semaphores are automatically reduced, and when release is used, semaphores increase.

When the semaphore is 0, the subsequent threads cannot get waitone, so they must wait for the previous thread to release through release.

 

Well, the following is an example:

 

<1> initialcount = 1, maximuncount = 10, waitone uses an indefinite wait.

 1   Namespace Leleapplication3
2 {
3 Class Program
4 {
5 Static Void Main ( String [] ARGs)
6 {
7
8 Thread T1 = New Thread (run1 );
9 T1.start ();
10
11 Thread t2 = New Thread (run2 );
12 T2.start ();
13
14 Console. Read ();
15 }
16
17 Static semaphore SEM = new semaphore (1, 10 );
18
19 Static Void Run1 ()
20 {
21 SEM. waitone ();
22
23 Console. writeline ( " Hello everyone, I'm run1. " );
24 }
25
26 Static Void Run2 ()
27 {
28 SEM. waitone ();
29
30 Console. writeline ( " Hello everyone, I'm run2. " );
31 }
32 }
33 }

We found that the T2 thread cannot be executed due to our tragedy. We know that waitone is equivalent to auto-subtraction semaphores. However, the default semaphores count is 1. Therefore, t2 must wait for T1 to be released through release.

 
1Static VoidRun1 ()
2{
3SEM. waitone ();
4
5Console. writeline ("Hello everyone, I'm run1.");
6
7SEM. Release ();
8}

 

Some may ask, didn't I set maximuncount = 10? Why didn't it play a role? Yes, it does not work by default. You must manually intervene in it,

We know that calling the release method is equivalent to auto-incrementing a semaphores. However, there is an overload in release. You can specify auto-incrementing to maximuncount semaphores. Here I am on the main thread.

Release (10) to see the effect.

 1   Namespace Leleapplication3
2 {
3 Class Program
4 {
5 Static Void Main ( String [] ARGs)
6 {
7
8 Thread T1 = New Thread (run1 );
9 T1.start ();
10
11 Thread t2 = New Thread (run2 );
12 T2.start ();
13
14 Thread. Sleep ( 1000 );
15
16 SEM. Release (10 );
17
18 Console. Read ();
19 }
20
21 Static Semaphore SEM = New Semaphore ( 1 ,10 );
22
23 Static Void Run1 ()
24 {
25 SEM. waitone ();
26
27 Console. writeline ( " Hello everyone, I'm run1. " );
28 }
29
30 Static Void Run2 ()
31 {
32 SEM. waitone ();
33
34 Console. writeline ( " Hello everyone, I'm run2. " );
35 }
36 }
37 }

<2> name semaphore and upgrade process interaction.

In the vs Object Browser, we found that semaphore is an inherited word waithandle, while waithandle encapsulates some synchronization mechanisms of Win32. So when we name semaphore

It will be visible in the system. The following is an exampleCodeCopy one copy and run twoProgram.

 1   Namespace Leleapplication3
2 {
3 Class Program
4 {
5 Static Void Main ( String [] ARGs)
6 {
7
8 Thread T1 = New Thread (run1 );
9 T1.start ();
10
11 Thread t2 = New Thread (run2 );
12 T2.start ();
13
14 Console. Read ();
15 }
16
17 Static semaphore SEM = new semaphore (3, 10, "cnblogs ");
18
19 Static Void Run1 ()
20 {
21 SEM. waitone ();
22
23 Console. writeline ( " Current Time: {0} Hello everyone, I am run1 " , Datetime. Now );
24 }
25
26 Static Void Run2 ()
27 {
28 SEM. waitone ();
29
30 Console. writeline ( " Current Time: {0} Hello everyone, I am run2 " , Datetime. Now );
31 }
32 }
33 }

 

 

Yes, I set three semaphores, so only three threads can hold waitone, and subsequent threads can only wait.

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.