/* * Spinlock.cpp * C++ Spinlock * Copyright (c) 2025 Daniel Hammer */ #pragma once #include #include namespace kcp { class Spinlock { std::atomic_flag atomic_flag{ATOMIC_FLAG_INIT}; uint64_t savedFlags = 0; public: void Acquire(); void Release(); // Explicit IRQ-save form for locks whose ownership is deliberately // handed across a context switch. The saved flags live on the caller's // stack (or in scheduler-owned per-context storage), not in the shared // lock object, so the resumed context restores its own interrupt state. uint64_t AcquireIrqSave(); void ReleaseIrqRestore(uint64_t flags); void ReleaseIrqNoRestore(); }; // Non-interrupt-disabling mutex for subsystems that are only called // from process/syscall context (never from interrupt handlers). // Keeps interrupts enabled while spinning and while held. class Mutex { std::atomic_flag flag{ATOMIC_FLAG_INIT}; public: void Acquire() { while (flag.test_and_set(std::memory_order_acquire)) { Arch::Pause(); } } bool TryAcquire() { return !flag.test_and_set(std::memory_order_acquire); } void Release() { flag.clear(std::memory_order_release); } }; };