forked from dragonflydb/dragonfly
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathintent_lock.h
53 lines (39 loc) · 1.14 KB
/
intent_lock.h
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
// Copyright 2022, DragonflyDB authors. All rights reserved.
// See LICENSE for licensing terms.
//
#include <assert.h>
#pragma once
namespace dfly {
// SHARED - can be acquired multiple times as long as other intents are absent.
// EXCLUSIVE - is acquired only if it's the only lock recorded.
// Transactions at the head of tx-queue are considered to be the ones that acquired the lock
class IntentLock {
public:
enum Mode { SHARED = 0, EXCLUSIVE = 1 };
// Returns true if lock was acquired. In any case, the intent is recorded.
bool Acquire(Mode m) {
++cnt_[m];
if (cnt_[1 ^ int(m)])
return false;
return m == SHARED || cnt_[EXCLUSIVE] == 1;
}
bool Check(Mode m) const {
unsigned s = cnt_[EXCLUSIVE];
if (s)
return false;
return (m == SHARED) ? true : IsFree();
}
void Release(Mode m, unsigned val = 1) {
assert(cnt_[m] >= val);
cnt_[m] -= val;
// return cnt_[m] == 0 ? cnt_[1 ^ int(m)] : 0;
}
bool IsFree() const {
return (cnt_[0] | cnt_[1]) == 0;
}
static const char* ModeName(Mode m);
void VerifyDebug();
private:
unsigned cnt_[2] = {0, 0};
};
} // namespace dfly