You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
62 lines
789 B
62 lines
789 B
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();
|
|
}
|
|
} |