summaryrefslogtreecommitdiffstats
path: root/src/common/shunique_lock.h
blob: 5f809e83a8b5b5254e5ff5cd668e03a3d2c00065 (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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab

#ifndef CEPH_COMMON_SHUNIQUE_LOCK_H
#define CEPH_COMMON_SHUNIQUE_LOCK_H

#include <mutex>
#include <shared_mutex>
#include <system_error>

namespace ceph {
// This is a 'lock' class in the style of shared_lock and
// unique_lock. Like shared_mutex it implements both Lockable and
// SharedLockable.

// My rationale is thus: one of the advantages of unique_lock is that
// I can pass a thread of execution's control of a lock around as a
// parameter. So that methods further down the call stack can unlock
// it, do something, relock it, and have the lock state be known by
// the caller afterward, explicitly. The shared_lock class offers a
// similar advantage to shared_lock, but each class is one or the
// other. In Objecter we have calls that in most cases need /a/ lock
// on the shared mutex, and whether it's shared or exclusive doesn't
// matter. In some circumstances they may drop the shared lock and
// reacquire an exclusive one. This could be handled by passing both a
// shared and unique lock down the call stack. This is vexacious and
// shameful.

// Wanting to avoid heaping shame and vexation upon myself, I threw
// this class together.

// This class makes no attempt to support atomic upgrade or
// downgrade. I don't want either. Matt has convinced me that if you
// think you want them you've usually made a mistake somewhere. It is
// exactly and only a reification of the state held on a shared mutex.

/// Acquire unique ownership of the mutex.
struct acquire_unique_t { };

/// Acquire shared ownership of the mutex.
struct acquire_shared_t { };

constexpr acquire_unique_t acquire_unique { };
constexpr acquire_shared_t acquire_shared { };

template<typename Mutex>
class shunique_lock {
public:
  typedef Mutex mutex_type;
  typedef std::unique_lock<Mutex> unique_lock_type;
  typedef std::shared_lock<Mutex> shared_lock_type;

  shunique_lock() noexcept : m(nullptr), o(ownership::none) { }

  // We do not provide a default locking/try_locking constructor that
  // takes only the mutex, since it is not clear whether to take it
  // shared or unique. We explicitly require the use of lock_deferred
  // to prevent Nasty Surprises.

  shunique_lock(mutex_type& m, std::defer_lock_t) noexcept
    : m(&m), o(ownership::none) { }

  shunique_lock(mutex_type& m, acquire_unique_t)
    : m(&m), o(ownership::none) {
    lock();
  }

  shunique_lock(mutex_type& m, acquire_shared_t)
    : m(&m), o(ownership::none) {
    lock_shared();
  }

  template<typename AcquireType>
  shunique_lock(mutex_type& m, AcquireType at, std::try_to_lock_t)
    : m(&m), o(ownership::none) {
    try_lock(at);
  }

  shunique_lock(mutex_type& m, acquire_unique_t, std::adopt_lock_t)
    : m(&m), o(ownership::unique) {
    // You'd better actually have a lock, or I will find you and I
    // will hunt you down.
  }

  shunique_lock(mutex_type& m, acquire_shared_t, std::adopt_lock_t)
    : m(&m), o(ownership::shared) {
  }

  template<typename AcquireType, typename Clock, typename Duration>
  shunique_lock(mutex_type& m, AcquireType at,
		const std::chrono::time_point<Clock, Duration>& t)
    : m(&m), o(ownership::none) {
    try_lock_until(at, t);
  }

  template<typename AcquireType, typename Rep, typename Period>
  shunique_lock(mutex_type& m, AcquireType at,
		const std::chrono::duration<Rep, Period>& dur)
    : m(&m), o(ownership::none) {
    try_lock_for(at, dur);
  }

  ~shunique_lock() {
    switch (o) {
    case ownership::none:
      return;
    case ownership::unique:
      m->unlock();
      break;
    case ownership::shared:
      m->unlock_shared();
      break;
    }
  }

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

  shunique_lock(shunique_lock&& l) noexcept : shunique_lock() {
    swap(l);
  }

  shunique_lock(unique_lock_type&& l) noexcept {
    if (l.owns_lock())
      o = ownership::unique;
    else
      o = ownership::none;
    m = l.release();
  }

  shunique_lock(shared_lock_type&& l) noexcept {
    if (l.owns_lock())
      o = ownership::shared;
    else
      o = ownership::none;
    m = l.release();
  }

  shunique_lock& operator=(shunique_lock&& l) noexcept {
    shunique_lock(std::move(l)).swap(*this);
    return *this;
  }

  shunique_lock& operator=(unique_lock_type&& l) noexcept {
    shunique_lock(std::move(l)).swap(*this);
    return *this;
  }

  shunique_lock& operator=(shared_lock_type&& l) noexcept {
    shunique_lock(std::move(l)).swap(*this);
    return *this;
  }

  void lock() {
    lockable();
    m->lock();
    o = ownership::unique;
  }

  void lock_shared() {
    lockable();
    m->lock_shared();
    o = ownership::shared;
  }

  void lock(ceph::acquire_unique_t) {
    lock();
  }

  void lock(ceph::acquire_shared_t) {
    lock_shared();
  }

  bool try_lock() {
    lockable();
    if (m->try_lock()) {
      o = ownership::unique;
      return true;
    }
    return false;
  }

  bool try_lock_shared() {
    lockable();
    if (m->try_lock_shared()) {
      o = ownership::shared;
      return true;
    }
    return false;
  }

  bool try_lock(ceph::acquire_unique_t) {
    return try_lock();
  }

  bool try_lock(ceph::acquire_shared_t) {
    return try_lock_shared();
  }

  template<typename Rep, typename Period>
  bool try_lock_for(const std::chrono::duration<Rep, Period>& dur) {
    lockable();
    if (m->try_lock_for(dur)) {
      o = ownership::unique;
      return true;
    }
    return false;
  }

  template<typename Rep, typename Period>
  bool try_lock_shared_for(const std::chrono::duration<Rep, Period>& dur) {
    lockable();
    if (m->try_lock_shared_for(dur)) {
      o = ownership::shared;
      return true;
    }
    return false;
  }

  template<typename Rep, typename Period>
  bool try_lock_for(ceph::acquire_unique_t,
		    const std::chrono::duration<Rep, Period>& dur) {
    return try_lock_for(dur);
  }

  template<typename Rep, typename Period>
  bool try_lock_for(ceph::acquire_shared_t,
		    const std::chrono::duration<Rep, Period>& dur) {
    return try_lock_shared_for(dur);
  }

  template<typename Clock, typename Duration>
  bool try_lock_until(const std::chrono::time_point<Clock, Duration>& time) {
    lockable();
    if (m->try_lock_until(time)) {
      o = ownership::unique;
      return true;
    }
    return false;
  }

  template<typename Clock, typename Duration>
  bool try_lock_shared_until(const std::chrono::time_point<Clock,
			     Duration>& time) {
    lockable();
    if (m->try_lock_shared_until(time)) {
      o = ownership::shared;
      return true;
    }
    return false;
  }

  template<typename Clock, typename Duration>
  bool try_lock_until(ceph::acquire_unique_t,
		      const std::chrono::time_point<Clock, Duration>& time) {
    return try_lock_until(time);
  }

  template<typename Clock, typename Duration>
  bool try_lock_until(ceph::acquire_shared_t,
		      const std::chrono::time_point<Clock, Duration>& time) {
    return try_lock_shared_until(time);
  }

  // Only have a single unlock method. Otherwise we'd be building an
  // Acme lock class suitable only for ravenous coyotes desparate to
  // devour a road runner. It would be bad. It would be disgusting. It
  // would be infelicitous as heck. It would leave our developers in a
  // state of seeming safety unaware of the yawning chasm of failure
  // that had opened beneath their feet that would soon transition
  // into a sickening realization of the error they made and a brief
  // moment of blinking self pity before their program hurled itself
  // into undefined behaviour and plummeted up the stack with core
  // dumps trailing behind it.

  void unlock() {
    switch (o) {
    case ownership::none:
      throw std::system_error((int)std::errc::resource_deadlock_would_occur,
			      std::generic_category());
      break;

    case ownership::unique:
      m->unlock();
      break;

    case ownership::shared:
      m->unlock_shared();
      break;
    }
    o = ownership::none;
  }

  // Setters

  void swap(shunique_lock& u) noexcept {
    std::swap(m, u.m);
    std::swap(o, u.o);
  }

  mutex_type* release() noexcept {
    o = ownership::none;
    mutex_type* tm = m;
    m = nullptr;
    return tm;
  }

  // Ideally I'd rather make a move constructor for std::unique_lock
  // that took a shunique_lock, but obviously I can't.
  unique_lock_type release_to_unique() {
    if (o == ownership::unique) {
      o = ownership::none;
      unique_lock_type tu(*m, std::adopt_lock);
      m = nullptr;
      return tu;
    } else if (o == ownership::none) {
      unique_lock_type tu(*m, std::defer_lock);
      m = nullptr;
      return tu;
    } else if (m == nullptr) {
      return unique_lock_type();
    }
    throw std::system_error((int)std::errc::operation_not_permitted,
			    std::generic_category());
  }

  shared_lock_type release_to_shared() {
    if (o == ownership::shared) {
      o = ownership::none;
      shared_lock_type ts(*m, std::adopt_lock);
      m = nullptr;
      return ts;
    } else if (o == ownership::none) {
      shared_lock_type ts(*m, std::defer_lock);
      m = nullptr;
      return ts;
    } else if (m == nullptr) {
      return shared_lock_type();
    }
    throw std::system_error((int)std::errc::operation_not_permitted,
			    std::generic_category());
    return shared_lock_type();
  }

  // Getters

  // Note that this returns true if the lock UNIQUE, it will return
  // false for shared
  bool owns_lock() const noexcept {
    return o == ownership::unique;
  }

  bool owns_lock_shared() const noexcept {
    return o == ownership::shared;
  }

  // If you want to make sure you have a lock of some sort on the
  // mutex, just treat as a bool.
  explicit operator bool() const noexcept {
    return o != ownership::none;
  }

  mutex_type* mutex() const noexcept {
    return m;
  }

private:
  void lockable() const {
    if (m == nullptr)
      throw std::system_error((int)std::errc::operation_not_permitted,
			      std::generic_category());
    if (o != ownership::none)
      throw std::system_error((int)std::errc::resource_deadlock_would_occur,
			      std::generic_category());
  }

  mutex_type*	m;
  enum struct ownership : uint8_t {
    none, unique, shared
      };
  ownership o;
};
} // namespace ceph

namespace std {
  template<typename Mutex>
  void swap(ceph::shunique_lock<Mutex> sh1,
	    ceph::shunique_lock<Mutex> sha) {
    sh1.swap(sha);
  }
} // namespace std

#endif // CEPH_COMMON_SHUNIQUE_LOCK_H