5天玩转C#并行和多线程编程 —— 第五天 多线程编程大总结

时间:2022-03-21 20:44:02

原文: 5天玩转C#并行和多线程编程 —— 第五天 多线程编程大总结

using System;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApp3
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("1.1 死锁问题 限时结束");
TaskMethod1_1();
Console.WriteLine("1.2 SpinLock 自旋锁");
TaskMethod1_2();
Console.Read();
}

private static void TaskMethod1_2()
{
SpinLock slock = new SpinLock(false);
long sum0 = 0;
long sum1 = 0;
long sum2 = 0;
Stopwatch sw = new Stopwatch();

Console.WriteLine("0. 不用多线程 累加开始");
sw.Start();
for (int i = 0; i < 100000; i++)
{
sum0 += i;
}
sw.Stop();
Console.WriteLine("0. 不用多线程 累加结束,耗时毫秒数:{0}", sw.ElapsedMilliseconds);

Console.WriteLine("1. 不加锁 累加开始");
sw.Start();
Parallel.For(0, 100000, i =>
{
sum1 += i;
});
sw.Stop();
Console.WriteLine("1. 不加锁 累加结束,耗时毫秒数:{0}", sw.ElapsedMilliseconds);

sw.Reset();
Console.WriteLine("2. SpinLock加锁 累加开始");
sw.Start();
Parallel.For(0, 100000, i =>
{
bool lockTaken = false;
try
{
slock.Enter(ref lockTaken);
sum2 += i;
}
finally
{
if (lockTaken)
slock.Exit(false);
}
});
sw.Stop();
Console.WriteLine("2. SpinLock加锁 累加结束,耗时毫秒数:{0}", sw.ElapsedMilliseconds);


object obj = new object();
long sum3 = 0;
sw.Reset();
Console.WriteLine("3. Lock加锁 累加开始");
sw.Start();
Parallel.For(0, 100000, i =>
{
lock (obj)
{
sum3 += i;
}
});
sw.Stop();
Console.WriteLine("3. Lock加锁 累加结束,耗时毫秒数:{0}", sw.ElapsedMilliseconds);

Console.WriteLine("Num0的值为:{0}", sum0);
Console.WriteLine("Num1的值为:{0}", sum1);
Console.WriteLine("Num2的值为:{0}", sum2);
Console.WriteLine("Num3的值为:{0}", sum3);

Console.Read();
}

private static void TaskMethod1_1()
{
Task[] tasks = new Task[2];
tasks[0] = Task.Factory.StartNew(() =>
{
Console.WriteLine("Task 1 Start running...");
while (true)
{
System.Threading.Thread.Sleep(1000);
}
Console.WriteLine("Task 1 Finished!");
});
tasks[1] = Task.Factory.StartNew(() =>
{
Console.WriteLine("Task 2 Start running...");
System.Threading.Thread.Sleep(2000);
Console.WriteLine("Task 2 Finished!");
});

Task.WaitAll(tasks, 5000);
for (int i = 0; i < tasks.Length; i++)
{
if (tasks[i].Status != TaskStatus.RanToCompletion)
{
Console.WriteLine("Task {0} Error!", i + 1);
}
}
}
}
}
5天玩转C#并行和多线程编程 —— 第五天 多线程编程大总结