thread sync

This commit is contained in:
2023-02-06 16:26:13 +09:00
parent 3c54eb1d0f
commit 4aa115a3d9
3 changed files with 78 additions and 0 deletions

View 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();
}
}

View 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>