多线程 整数 +1; 有如下的写法:
while (true) { var mre = new AutoResetEvent(true); int m = 0; for (int i = 0; i < 200; i++) { Task.Run(() => { mre.WaitOne(); m++; mre.Set(); }); } Console.ReadLine(); Console.WriteLine($"waiting...{m}"); } while (true) { var mut = new Mutex(); int m = 0; for (int i = 0; i < 200; i++) { _ = Task.Run(() => { mut.WaitOne(); m++; mut.ReleaseMutex(); }); } Console.ReadLine(); Console.WriteLine($"waiting,mutex...{m}"); } while (true) { SpinLock spinLock = new SpinLock(false); int m = 0; for (int i = 0; i < 200; i++) { bool sp = false; _ = Task.Run(() => { try { spinLock.Enter(ref sp); m++; } catch (global::System.Exception e) { global::System.Console.WriteLine(e.Message); } finally { if (sp) spinLock.Exit(); } }); } Console.ReadLine(); Console.WriteLine($"waiting...{m}"); } while (true) { int m = 0; for (int i = 0; i < 200; i++) { Task.Run(() => { Interlocked.Increment(ref m); }); } Console.ReadLine(); Console.WriteLine($"waiting...{m}"); } while (true) // 不正确 { int m = 0; for (int i = 0; i < 200; i++) { Task.Run(() => { m++; }); } Console.ReadLine(); Console.WriteLine($"waiting...{m}"); }