libcruft-util/thread/spinlock.hpp
Danny Robson 01094611eb thread: add minimal thread primitives for win32
This allows us to get around the lack of these types under MinGW
2019-06-22 15:46:34 +10:00

47 lines
1.3 KiB
C++

/*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* Copyright 2018-2019 Danny Robson <danny@nerdcruft.net>
*/
#pragma once
#include <atomic>
namespace cruft::thread {
/// A CPU intensive, but lower latency, lock.
///
/// std::atomic_flag seems like it might have been a good option on which
/// to base our implementation, but it appears potentially expensive to
/// spin over without a cheap read operation.
///
/// Satisfies BasicLockable.
///
/// NOTE: All move operations assume that either the lock is held by the
/// client performing the move, or that is not held by any client.
class spinlock {
public:
spinlock ();
~spinlock ();
spinlock (spinlock &&) noexcept;
spinlock& operator= (spinlock &&) noexcept;
spinlock (const spinlock&) = delete;
spinlock& operator= (const spinlock&) = delete;
void lock ();
void unlock ();
private:
static_assert (
::std::atomic<bool>::is_always_lock_free,
"we require a lock free primitive or the entire point is moot"
);
::std::atomic<bool> held;
};
};