summaryrefslogtreecommitdiff
path: root/euler/include/std/unique_lock.hpp
blob: 14b3645d696588d98bcf5f55074a91ddd3cf6e83 (plain) (blame)
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
#pragma once

namespace std {

  template <class Mutex>
  class unique_lock {

    Mutex *the_mutex;
    bool has_locked;

  public:
    inline unique_lock() noexcept : the_mutex(0) {}

    unique_lock(const unique_lock &other) = delete;

    inline unique_lock(unique_lock &&other) noexcept
    : the_mutex(other.the_mutex), has_locked(other.has_locked) {
      other.the_mutex = 0;
    }

    inline explicit unique_lock(Mutex &m)
    : the_mutex(&m), has_locked(true) {
      the_mutex->lock();
    }

    inline ~unique_lock() {
      if (the_mutex && has_locked)
        the_mutex->unlock();
    }

    unique_lock &operator =(const unique_lock &other) = delete;

    inline unique_lock &operator =(unique_lock &&other) {
      if (the_mutex && has_locked)
        the_mutex->unlock();
      the_mutex = other.the_mutex;
      has_locked = other.has_locked;
      other.the_mutex = 0;
    }

    inline void lock() {
      the_mutex->lock();
      has_locked = true;
    }

    inline void unlock() {
      the_mutex->unlock();
      has_locked = false;
    }

  };

}