/* * Process Hacker - * spinlock * * Copyright (C) 2009 wj32 * * This file is part of Process Hacker. * * Process Hacker is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Process Hacker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Process Hacker. If not, see . */ using System; using System.Threading; namespace ProcessHacker.Common.Threading { /// /// Represents a spinlock, a high-performance mutual exclusion lock. /// public struct SpinLock { public struct SpinLockContext : IDisposable { private bool _disposed; private SpinLock _spinLock; internal SpinLockContext(SpinLock spinLock) { _spinLock = spinLock; _spinLock.Acquire(); _disposed = false; } public void Dispose() { if (!_disposed) { _spinLock.Release(); _disposed = true; } } } private int _value; /// /// Acquires the spinlock. /// public void Acquire() { if (Interlocked.CompareExchange(ref _value, 1, 0) == 0) return; if (NativeMethods.SpinEnabled) { while (Interlocked.CompareExchange(ref _value, 1, 0) == 1) Thread.SpinWait(8); } else { while (Interlocked.CompareExchange(ref _value, 1, 0) == 1) Thread.Sleep(0); } } /// /// Acquires the spinlock using a context object. /// /// A disposable context object. public SpinLockContext AcquireContext() { return new SpinLockContext(this); } /// /// Releases the spinlock. /// public void Release() { Interlocked.Exchange(ref _value, 0); } } }