summaryrefslogtreecommitdiff
path: root/kernel/src/generic/lock/mutex.hpp
blob: d48b0b4745e3f3b8a60de67a98355773e6c3b1cd (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
#pragma once
#include <cstdint>
#include <atomic>

#include <generic/lock/spinlock.hpp>
#include <generic/scheduling.hpp>

namespace locks {
    class mutex {
    private:
        std::atomic_flag flag = ATOMIC_FLAG_INIT;

    public:
        void lock() {
            if(locks::is_disabled)
                return;
                    
            while (flag.test_and_set(std::memory_order_acquire)) {
                process::yield();
            }
        }

        void unlock() {
            flag.clear(std::memory_order_release);
        }

        bool test() {
            return flag.test();
        }

        bool try_lock() {
            return !flag.test_and_set(std::memory_order_acquire);
        }
    };
};