@anonymous/

SourFormalMedia

C++

No description

fork
loading
Files
  • main.cpp
main.cpp
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
#include <mutex>
#include <thread>
#include <stdio.h>

#define LOG(block)                         \
    printf("%s: %s start\n", tag, #block); \
    block;                                 \
    printf("%s: %s done\n", tag, #block)

#define LOGC(block)                                   \
    printf("%s: %s start, c = %d\n", tag, #block, c); \
    block;                                            \
    printf("%s: %s done, c = %d\n", tag, #block, c)

class semaphore
{
public:
    semaphore(int c) : c(c)
    {
        if (c < 1) d.lock();
    }

    void wait(const char *tag)
    {
        LOG(d.lock());
        LOG(m.lock());
        LOGC(c--);
        if (c > 0)
        {
            LOG(d.unlock());
        }
        LOG(m.unlock());
    }

    void post(const char *tag)
    {
        LOG(m.lock());
        LOGC(c++);
        if (c == 1)
        {
            LOG(d.unlock());
        }
        LOG(m.unlock());
    }

private:
    int c;
    std::mutex m;
    std::mutex d;
};

semaphore sem(0);

void foo(const char *tag)
{
    LOG(sem.wait(tag));
}

int main()
{
    const char *tag;

    std::thread t1(foo, "thread 1");
    std::thread t2(foo, "thread 2");

    tag = "main (1)";
    LOG(sem.post(tag));

    tag = "main (2)";
    LOG(sem.post(tag));

    t1.join();
    t2.join();

    printf("main: done\n");
    return 0;
}