summaryrefslogtreecommitdiffhomepage
path: root/dev/kernel/KernelKit/LockDelegate.h
blob: 745abaf09507ff846c7526130fb2d5907ae855da (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
/* -------------------------------------------

  Copyright (C) 2024-2025, Amlal El Mahrouss, licensed under the Apache 2.0 license.

------------------------------------------- */

#pragma once

#include <NeKit/Atom.h>
#include <NeKit/Defines.h>

namespace Kernel {
enum {
  kLockInvalid  = 0,
  kLockDone     = 200,
  kLockTimedOut = 300,
  kLockCount    = 3,
};

/// @brief Lock condition pointer.
typedef Boolean* LockPtr;

/// @brief Locking delegate class, hangs until limit.
/// @tparam N the amount of cycles to wait.
template <SizeT N>
class LockDelegate final {
 public:
  LockDelegate() = delete;

 public:
  explicit LockDelegate(LockPtr expr) {
    auto spin = 0U;

    while (spin < N) {
      if (*expr) {
        fLockStatus | kLockDone;
        break;
      }

      ++spin;
    }

    if (spin > N) fLockStatus | kLockTimedOut;
  }

  ~LockDelegate() = default;

  LockDelegate& operator=(const LockDelegate&) = delete;
  LockDelegate(const LockDelegate&)            = delete;

  bool Done() { return fLockStatus[kLockDone] == kLockDone; }

  bool HasTimedOut() { return fLockStatus[kLockTimedOut] != kLockTimedOut; }

 private:
  Atom<UInt> fLockStatus;
};
}  // namespace Kernel