The parallel development of synchronization mechanisms (lower) 8 days Fun parallel development - the fifth day synchronization mechanism (lower)

Original: 8 days Fun parallel development - the fifth day synchronization mechanism (lower)

 

   

     One, we went down to undertake a synchronization mechanism .net4.0 in, yes, when there is a parallel computing when other lightweight synchronization mechanism came into being, in this one semaphore

A series of lightweight, continue to introduce three semaphore following CountdownEvent, SemaphoreSlim, ManualResetEventSlim today.

 

A: CountdownEvent

     Synchronization primitives that use state of the signal is very suitable in a dynamic fork, join scenario, which uses "signal counter" manner, such as such, can only accommodate a mahjong table 4

People playing mahjong, if then people would also like to rub a chance, then he must wait until the person gone on a mahjong table. Well, this is a simple signal counting mechanism, from a technical angle

Degree up it is up to the definition of the number of threads can enter the key code.

     But at CountdownEvent more cattle X in that we can dynamically change the size of the "signal counts" of such a moment can accommodate eight threads, it has four, and about 10,

What good does it do this? Or to undertake the article said, such a task requires 1w load of data, then this may happen.

 

Load User table: the amount of data the user table, we need to open five task.

Load Product table: Table products relatively more data, we need to open eight task after the calculation.

Load order table: As my website orders rich, you need to open 12 task after the calculation.

 

Previous article also said, we need to coordinate task synchronization to load data in a multi-stage, then how to deal with 5,8,12 here, fortunately, CountdownEvent provided us

You can dynamically modify the solution.

Copy the code
  The using System.Collections.Concurrent. 1; 
2 System.Threading.Tasks the using;
. 3 the using the System;
. 4 the using the System.Diagnostics;
. 5 the using the System.Collections.Generic;
. 6 the using the System.Linq;
. 7 the using the System.Threading;
. 8
. 9 class Program
10 {
11 // default size is receiving "hardware thread" the number
12 is static CountdownEvent CDE = new new CountdownEvent (Environment.ProcessorCount);
13 is
14 static void the Main (String [] args)
15 {
16 // User loading table requires 5 task
. 17 userTaskCount = var. 5;
18 is
. 19 // reset signal
20 is cde.Reset (userTaskCount);
21 is
22 is for (int I = 0; I <userTaskCount; I ++)
23 is {
Task.Factory.StartNew 24 ((obj) =>
25 {
26 is LoadUser (obj);
27}, I);
28}
29
30 // wait for all tasks finished
31 is cde.Wait ();
32
33 is Console.WriteLine ( "\ nUser table data is fully loaded \ n-!");
34 is
35 8 // required product loading task
36 productTaskCount = var. 8;
37 [
38 is // reset signal
39 cde.Reset (productTaskCount);
40
41 is for (int 0 = I; I <productTaskCount; I ++)
42 is {
43 is Task.Factory.StartNew ((obj) =>
44 is {
45 LoadProduct (obj);
46 is}, I);
47}
48
49 cde.Wait ();
50
51 is Console.WriteLine ( "\ nProduct table data is fully loaded \ n-!");
52 is
53 // 12 loading order required task
54 is var = 12 is orderTaskCount;
55
56 is // reset signal
57 is cde.Reset (orderTaskCount);
58
59 for (int I = 0; I <orderTaskCount; I ++)
60 {
61 is the Task. Factory.StartNew ((obj) =>
62 is {
63 is LoadOrder (obj);
64}, I);
65}
66
67 cde.Wait ();
68
! 69 Console.WriteLine ( "\ Norder table data is fully loaded \ n ");
70
71 is Console.WriteLine (" \ n-(* ^ __ ^ *) hee, Congratulations, all the data loaded \ n-");
72
73 is Console.Read ();
74}
75
76 static void LoadUser ( obj Object)
77 {
78 the try
79 {
80 Console.WriteLine ( "current task: {0} User part loading data!", obj);
} 81
82 the finally
83 {
84 cde.Signal ();
85}
86}
87
88 static void LoadProduct (Object obj)
89 {
90 the try
91 is {
92 Console.WriteLine ( "current task: {0} is the partial data loading Product! ", obj);
93}
94 the finally
95 {
96 cde.Signal ();
97}
98}
99
100 static void LoadOrder (Object obj)
101 {
102 the try
103 {
104 Console.WriteLine (" current task: is {0} load Order partial data ", obj);!
105}
106 the finally
107 {
108 cde.Signal ();
109}
110}
111}
Copy the code


We see that there are two main methods: Wait and Signal. Each call Signal walking the equivalent of a person on the mahjong table until everyone had to rub Mahjong wait to release it, the same to be here

Note also that the existence of "time out" problems, especially in parallel computing, lightweight do not provide us with a mechanism to "cancel mark", which is not present in the weight class, such as the following

Overloaded public bool Wait (int millisecondsTimeout, CancellationToken cancellationToken), describes the specific use of an article before you can see.

 

二:SemaphoreSlim

     Before .net 4.0, framework, there is a heavyweight Semaphore, people can cross-process synchronization, lightweight ye not, explain msdn it is: can simultaneously access restrictions

The number of threads of a resource or resource pool. On its heavyweight demo, I was on a series of presentations, you can also be understood as a function plus CountdownEvent is SemaphoreSlim

Strong version, well, for example the use of a lightweight.

Copy the code
 1 using System.Collections.Concurrent;
2 using System.Threading.Tasks;
3 using System;
4 using System.Diagnostics;
5 using System.Collections.Generic;
6 using System.Linq;
7 using System.Threading;
8
9 class Program
10 {
11 static SemaphoreSlim slim = new SemaphoreSlim(Environment.ProcessorCount, 12);
12
13 static void Main(string[] args)
14 {
15 for (int i = 0; i < 12; i++)
16 {
17 Task.Factory.StartNew((obj) =>
18 {
19 Run(obj);
20 }, i);
21 }
22
23 Console.Read();
24 }
25
26 static void Run(object obj)
27 {
Slim.Wait 28 ();
29
30 Console.WriteLine ( "Current Time: {1} {0} task has entered.", The DateTime.Now, obj);
31 is
32 // here busy3s in
33 Thread.Sleep (3000) ;
34 is
35 slim.Release ();
36}
37 [}
Copy the code


Also, to prevent a deadlock situation, we need to know "timeout and cancel mark" solutions, such as SemaphoreSlim given dead "thread requests" and actually reduces the scalability,

So, to test the water at risk, need to be cautious, you feel the need to use it at the time.

 

三: ManualResetEventSlim

     I believe it's weight class we all know ManualReset, while the other uses a lightweight "spin-wait" + "kernel wait", that is to say the first use of "spin-wait approach" wait,

Until another task calls the set method to release it. If you can not wait for tardy release, the task will enter the waiting-based kernel, so that if we know the waiting time is short, mining

With a lightweight version will have better performance, probably this principle, the following small example.

Copy the code
 1 using System.Collections.Concurrent;
2 using System.Threading.Tasks;
3 using System;
4 using System.Diagnostics;
5 using System.Collections.Generic;
6 using System.Linq;
7 using System.Threading;
8
9 class Program
10 {
11 //2047:自旋的次数
12 static ManualResetEventSlim mrs = new ManualResetEventSlim(false, 2047);
13
14 static void Main(string[] args)
15 {
16
17 for (int i = 0; i < 12; i++)
18 {
19 Task.Factory.StartNew((obj) =>
20 {
21 Run(obj);
22 }, i);
23 }
24
25 Console.WriteLine("当前时间:{0}我是主线程{1},你们这些任务都等2s执行吧:\n",
The DateTime.Now 26 is,
27 Thread.CurrentThread.ManagedThreadId);
28 the Thread.Sleep (2000);
29
30 mrs.Set ();
31 is
32 Console.Read ();
33 is}
34 is
35 static void the Run (Object obj)
36 {
mrs.Wait 37 [();
38 is
39 Console.WriteLine ( "current time: {1} {0} task has entered.", the DateTime.Now, obj);
40}
41 is}
Copy the code

 

Guess you like

Origin www.cnblogs.com/zhang1f/p/11162812.html