From 8722a9920c1f6119bf6e769cba270e63097f8e25 Mon Sep 17 00:00:00 2001 From: chai <215380520@qq.com> Date: Thu, 23 May 2024 10:08:29 +0800 Subject: + astar project --- .../com.arongranberg.astar/Utilities/SpinLock.cs | 28 ++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 Other/AstarPathfindingDemo/Packages/com.arongranberg.astar/Utilities/SpinLock.cs (limited to 'Other/AstarPathfindingDemo/Packages/com.arongranberg.astar/Utilities/SpinLock.cs') diff --git a/Other/AstarPathfindingDemo/Packages/com.arongranberg.astar/Utilities/SpinLock.cs b/Other/AstarPathfindingDemo/Packages/com.arongranberg.astar/Utilities/SpinLock.cs new file mode 100644 index 0000000..88b9092 --- /dev/null +++ b/Other/AstarPathfindingDemo/Packages/com.arongranberg.astar/Utilities/SpinLock.cs @@ -0,0 +1,28 @@ +using System.Threading; + +namespace Pathfinding.Jobs { + /// + /// Spin lock which can be used in Burst. + /// Good when the lock is generally uncontested. + /// Very inefficient when the lock is contested. + /// + public struct SpinLock { + private volatile int locked; + + public void Lock () { + while (Interlocked.CompareExchange(ref locked, 1, 0) != 0) + Unity.Burst.Intrinsics.Common.Pause(); // spin + + // We need to ensure that any optimizer does not reorder loads to before we aquire the lock. + System.Threading.Thread.MemoryBarrier(); + } + + public void Unlock () { + // We need a memory barrier to ensure that all writes are visible to other threads, before we unlock. + // We also need to ensure that any optimizer does not reorder stores to after the unlock. + System.Threading.Thread.MemoryBarrier(); + // Release the lock by writing 0 to it. Use atomics to make it immediately visible to other threads. + if (Interlocked.Exchange(ref locked, 0) == 0) throw new System.InvalidOperationException("Trying to unlock a lock which is not locked"); + } + } +} -- cgit v1.1-26-g67d0