blob: 373f4c0e13b986759e667238d9bb9d20eff2e8da (
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
#include <util/system/condvar.h>
#include <util/system/mutex.h>
class TLatch {
private:
// 0 for unlocked, 1 for locked
TAtomic Locked;
TMutex Mutex;
TCondVar CondVar;
public:
TLatch()
: Locked(0)
{
}
void Wait() {
// optimistic path
if (AtomicGet(Locked) == 0) {
return;
}
TGuard<TMutex> guard(Mutex);
while (AtomicGet(Locked) == 1) {
CondVar.WaitI(Mutex);
}
}
bool TryWait() {
return AtomicGet(Locked) == 0;
}
void Unlock() {
// optimistic path
if (AtomicGet(Locked) == 0) {
return;
}
TGuard<TMutex> guard(Mutex);
AtomicSet(Locked, 0);
CondVar.BroadCast();
}
void Lock() {
AtomicSet(Locked, 1);
}
bool IsLocked() {
return AtomicGet(Locked);
}
};
|