aboutsummaryrefslogtreecommitdiff
path: root/libs/kstd/include/kstd/mutex
blob: cf8549f1a8419b087f94e213568bb57b198a0b37 (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
59
60
#ifndef KSTD_MUTEX_HPP
#define KSTD_MUTEX_HPP

#include <atomic>

namespace kstd
{
  /**
   * @brief Custom mutex implementation, that simply wraps an atomic boolean to keep track if the mutex is already in
   * use by another thread or not.
   */
  struct mutex
  {
    /**
     * @brief Defaulted constructor.
     */
    mutex() = default;

    /**
     * @brief Defaulted destructor.
     */
    ~mutex() = default;

    /**
     * @brief Deleted copy constructor.
     */
    mutex(const mutex &) = delete;

    /**
     * @brief Deleted assignment operator.
     */
    mutex & operator=(const mutex &) = delete;

    /**
     * @brief Lock the mutex (blocks for as long as it is not available).
     */
    [[gnu::section(".stl_text")]]
    auto lock() -> void;

    /**
     * @brief Try to lock the mutex (non-blocking).
     *
     * @return True if lock has been acquired and false otherwise.
     */
    [[gnu::section(".stl_text")]]
    auto try_lock() -> bool;

    /**
     * @brief Unlock the mutex.
     */
    [[gnu::section(".stl_text")]]
    auto unlock() -> void;

  private:
    std::atomic<bool> locked = {false};  // Atomic boolean to track if mutex is locked or not.
  };

}  // namespace kstd

#endif