aboutsummaryrefslogtreecommitdiff
path: root/libbutl/mingw-mutex.hxx
blob: 375a5724215cf0fdf066c69bf02655cf277d4fd1 (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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
/**
* std::mutex et al implementation for MinGW-w64
*
* Copyright (c) 2013-2016 by Mega Limited, Auckland, New Zealand
* Copyright (c) 2022 the build2 authors
*
* Licensed under the simplified (2-clause) BSD License.
* You should have received a copy of the license along with this
* program.
*
* This code is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*/

#ifndef LIBBUTL_MINGW_MUTEX_HXX
#define LIBBUTL_MINGW_MUTEX_HXX

#if !defined(__cplusplus) || (__cplusplus < 201402L)
#  error C++14 compiler required
#endif

#if !defined(_WIN32_WINNT) || _WIN32_WINNT < 0x0601
#  error _WIN32_WINNT should be 0x0601 (Windows 7) or greater
#endif

#include <chrono>
#include <system_error>
#include <atomic>

#include <mutex>

#include <synchapi.h>       //  For InitializeCriticalSection, etc.
#include <errhandlingapi.h> //  For GetLastError
#include <handleapi.h>

namespace mingw_stdthread
{
  // To make this namespace equivalent to the thread-related subset of std,
  // pull in the classes and class templates supplied by std but not by this
  // implementation.
  //
  using std::lock_guard;
  using std::unique_lock;
  using std::adopt_lock_t;
  using std::defer_lock_t;
  using std::try_to_lock_t;
  using std::adopt_lock;
  using std::defer_lock;
  using std::try_to_lock;

  class recursive_mutex
  {
    CRITICAL_SECTION mHandle;
  public:
    typedef LPCRITICAL_SECTION native_handle_type;
    native_handle_type native_handle() {return &mHandle;}
    recursive_mutex() noexcept : mHandle()
    {
      InitializeCriticalSection(&mHandle);
    }
    recursive_mutex (const recursive_mutex&) = delete;
    recursive_mutex& operator=(const recursive_mutex&) = delete;
    ~recursive_mutex() noexcept
    {
      DeleteCriticalSection(&mHandle);
    }
    void lock()
    {
      EnterCriticalSection(&mHandle);
    }
    void unlock()
    {
      LeaveCriticalSection(&mHandle);
    }
    bool try_lock()
    {
      return (TryEnterCriticalSection(&mHandle)!=0);
    }
  };

  // Slim Reader-Writer (SRW)-based implementation that requires Windows 7.
  //
#if !defined(SRWLOCK_INIT)
#error SRWLOCK_INIT macro is not defined
//#define SRWLOCK_INIT {0}
#endif

  class mutex
  {
  protected:
    SRWLOCK mHandle;
  public:
    typedef PSRWLOCK native_handle_type;
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wzero-as-null-pointer-constant"
    constexpr mutex () noexcept : mHandle(SRWLOCK_INIT) { }
#pragma GCC diagnostic pop
    mutex (const mutex&) = delete;
    mutex & operator= (const mutex&) = delete;
    void lock ()
    {
      AcquireSRWLockExclusive(&mHandle);
    }
    void unlock ()
    {
      ReleaseSRWLockExclusive(&mHandle);
    }
    //  TryAcquireSRW functions are a Windows 7 feature.
    bool try_lock ()
    {
      BOOL ret = TryAcquireSRWLockExclusive(&mHandle);
      return ret;
    }
    native_handle_type native_handle ()
    {
        return &mHandle;
    }
  };

  class recursive_timed_mutex
  {
    static constexpr DWORD kWaitAbandoned = 0x00000080l;
    static constexpr DWORD kWaitObject0 = 0x00000000l;
    static constexpr DWORD kInfinite = 0xffffffffl;
    inline bool try_lock_internal (DWORD ms) noexcept
    {
      DWORD ret = WaitForSingleObject(mHandle, ms);

      /*
        @@ TODO
#ifndef NDEBUG
      if (ret == kWaitAbandoned)
      {
        using namespace std;
        fprintf(stderr, "FATAL: Thread terminated while holding a mutex.");
        terminate();
      }
#endif
      */

      return (ret == kWaitObject0) || (ret == kWaitAbandoned);
    }
  protected:
    HANDLE mHandle;
  public:
    typedef HANDLE native_handle_type;
    native_handle_type native_handle() const {return mHandle;}
    recursive_timed_mutex(const recursive_timed_mutex&) = delete;
    recursive_timed_mutex& operator=(const recursive_timed_mutex&) = delete;
    recursive_timed_mutex(): mHandle(CreateMutex(NULL, FALSE, NULL)) {}
    ~recursive_timed_mutex()
    {
      CloseHandle(mHandle);
    }
    void lock()
    {
      DWORD ret = WaitForSingleObject(mHandle, kInfinite);

      /*
        @@ TODO

//    If (ret == WAIT_ABANDONED), then the thread that held ownership was
//  terminated. Behavior is undefined, but Windows will pass ownership to this
//  thread.
#ifndef NDEBUG
        if (ret == kWaitAbandoned)
        {
            using namespace std;
            fprintf(stderr, "FATAL: Thread terminated while holding a mutex.");
            terminate();
        }
#endif
      */

      if ((ret != kWaitObject0) && (ret != kWaitAbandoned))
      {
        throw std::system_error(GetLastError(), std::system_category());
      }
    }
    void unlock()
    {
      if (!ReleaseMutex(mHandle))
        throw std::system_error(GetLastError(), std::system_category());
    }
    bool try_lock()
    {
      return try_lock_internal(0);
    }
    template <class Rep, class Period>
    bool try_lock_for(const std::chrono::duration<Rep,Period>& dur)
    {
      using namespace std::chrono;
      auto timeout = duration_cast<milliseconds>(dur).count();
      while (timeout > 0)
      {
        constexpr auto kMaxStep = static_cast<decltype(timeout)>(kInfinite-1);
        auto step = (timeout < kMaxStep) ? timeout : kMaxStep;
        if (try_lock_internal(static_cast<DWORD>(step)))
          return true;
        timeout -= step;
      }
      return false;
    }
    template <class Clock, class Duration>
    bool try_lock_until(const std::chrono::time_point<Clock,Duration>& timeout_time)
    {
      return try_lock_for(timeout_time - Clock::now());
    }
  };

  typedef recursive_timed_mutex timed_mutex;
}

#endif // LIBBUTL_MINGW_MUTEX_HXX