aboutsummaryrefslogtreecommitdiffstats
path: root/library/cpp/messagebus/misc/test_sync.h
blob: 8e5aa212aa98e0ecde37334bb5cee33856d723e5 (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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#pragma once 
 
#include <util/system/condvar.h>
#include <util/system/mutex.h> 
 
class TTestSync { 
private: 
    unsigned Current; 
 
    TMutex Mutex; 
    TCondVar CondVar; 

public: 
    TTestSync() 
        : Current(0) 
    {
    }
 
    void Inc() { 
        TGuard<TMutex> guard(Mutex); 
 
        DoInc(); 
        CondVar.BroadCast(); 
    } 
 
    unsigned Get() { 
        TGuard<TMutex> guard(Mutex); 
 
        return Current; 
    } 
 
    void WaitFor(unsigned n) { 
        TGuard<TMutex> guard(Mutex); 
 
        Y_VERIFY(Current <= n, "too late, waiting for %d, already %d", n, Current);
 
        while (n > Current) { 
            CondVar.WaitI(Mutex); 
        } 
    } 
 
    void WaitForAndIncrement(unsigned n) { 
        TGuard<TMutex> guard(Mutex); 
 
        Y_VERIFY(Current <= n, "too late, waiting for %d, already %d", n, Current);
 
        while (n > Current) { 
            CondVar.WaitI(Mutex); 
        } 
 
        DoInc(); 
        CondVar.BroadCast(); 
    } 
 
    void CheckAndIncrement(unsigned n) { 
        TGuard<TMutex> guard(Mutex); 
 
        Y_VERIFY(Current == n, "must be %d, currently %d", n, Current);
 
        DoInc(); 
        CondVar.BroadCast(); 
    } 
 
    void Check(unsigned n) { 
        TGuard<TMutex> guard(Mutex); 
 
        Y_VERIFY(Current == n, "must be %d, currently %d", n, Current);
    } 
 
private: 
    void DoInc() { 
        unsigned r = ++Current; 
        Y_UNUSED(r);
    } 
};