-
Notifications
You must be signed in to change notification settings - Fork 0
/
With_SYNCHRONIZATION.cs
48 lines (44 loc) · 1.18 KB
/
With_SYNCHRONIZATION.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
using System;
using System.Text;
using System.Threading;
/* Synchronization is a technique that allows only one thread to access
* the resource for the particular time. No other thread can
* interrupt until the assigned thread finishes its task.
*
* ---- Consistency Maintain
----- No Thread Interference
We can use C# lock keyword to execute program synchronously.
It is used to get lock for the current thread, execute the task and then release the lock.
It ensures that other thread does not interrupt the execution until the execution finish.
Here, we are creating two examples that executes asynchronously and synchronously.
*/
//* With SYNCHRONIZATION *//
/*using the lock Keyword*/
namespace ConsoleApp51
{
class Printer
{
public void PrintTable()
{
lock (this)
{
for (int i = 0; i <= 10; i++)
{
Thread.Sleep(100);
Console.WriteLine(i);
}
}
}
}
public class Program
{
public static void Main()
{
Printer p = new Printer();
Thread t1 = new Thread(new ThreadStart(p.PrintTable));
Thread t2 = new Thread(new ThreadStart(p.PrintTable));
t1.Start();
t2.Start();
}
}
}