yy1717
2023-03-31 4bd08f0355b6b2cf3c027202d5ad301b4e182953
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
//
// Created by YY on 2022/12/30.
//
 
#ifndef MYAPPLICATION3_SEMAPHORE_H
#define MYAPPLICATION3_SEMAPHORE_H
 
#include <mutex>
#include <condition_variable>
 
namespace ilovers{
    class semaphore {
    public:
        semaphore(int value=1): count{value}, wakeups{0} {}
 
        void wait(void) {
            std::unique_lock<std::mutex> lock{mutex};
            if (--count<0) { // count is not enough ?
                condition.wait(lock, [&]()->bool{ return wakeups>0;}); // suspend and wait ...
                --wakeups;  // ok, me wakeup !
            }
        }
        void signal(void) {
            std::lock_guard<std::mutex> lock{mutex};
            if(++count<=0) { // have some thread suspended ?
                ++wakeups;
                condition.notify_one(); // notify one !
            }
        }
 
    private:
        int count;
        int wakeups;
        std::mutex mutex;
        std::condition_variable condition;
    };
};
 
#endif //MYAPPLICATION3_SEMAPHORE_H