thread sync
This commit is contained in:
62
MultiThread/ThreadSyncTest/Program.cs
Normal file
62
MultiThread/ThreadSyncTest/Program.cs
Normal file
@@ -0,0 +1,62 @@
|
||||
namespace ThreadSyncTest;
|
||||
|
||||
internal class Program
|
||||
{
|
||||
static void Main(string[] args)
|
||||
{
|
||||
int num = 0;
|
||||
object obj = new object();
|
||||
|
||||
Thread t1 = new Thread(() =>
|
||||
{
|
||||
for (int i = 0; i < 1000000; i++)
|
||||
{
|
||||
lock (obj)
|
||||
{
|
||||
num++;
|
||||
}
|
||||
|
||||
//try
|
||||
//{
|
||||
// Monitor.Enter(obj);
|
||||
// num++; // Critical section
|
||||
//}
|
||||
//finally
|
||||
//{
|
||||
// Monitor.Exit(obj);
|
||||
//}
|
||||
}
|
||||
});
|
||||
|
||||
Thread t2 = new Thread(() =>
|
||||
{
|
||||
for (int i = 0; i < 1000000; i++)
|
||||
{
|
||||
lock (obj)
|
||||
{
|
||||
num++;
|
||||
}
|
||||
|
||||
//try
|
||||
//{
|
||||
// Monitor.Enter(obj);
|
||||
// num++; // Critical section
|
||||
//}
|
||||
//finally
|
||||
//{
|
||||
// Monitor.Exit(obj);
|
||||
//}
|
||||
}
|
||||
});
|
||||
|
||||
t1.Start();
|
||||
t2.Start();
|
||||
|
||||
t1.Join();
|
||||
t2.Join();
|
||||
|
||||
Console.WriteLine(num);
|
||||
|
||||
Console.ReadLine();
|
||||
}
|
||||
}
|
10
MultiThread/ThreadSyncTest/ThreadSyncTest.csproj
Normal file
10
MultiThread/ThreadSyncTest/ThreadSyncTest.csproj
Normal file
@@ -0,0 +1,10 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net6.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
</PropertyGroup>
|
||||
|
||||
</Project>
|
Reference in New Issue
Block a user