wangrong
2025-01-03 2c4b8838f89bebca97615c5f0bac2c58e0349771
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
#pragma once
 
#include <condition_variable>
#include <mutex>
 
namespace vp_utils {
    // semaphore used to resume/pause loop structure, it blocks thread while received unactive signal and unblock thread while received active signal.
    // refer to vp_semaphore also
    class vp_gate
    {
    public:
        vp_gate() {
            opened_ = false;
        }
 
        void open() {
            std::unique_lock<std::mutex> lock(mutex_);
            opened_ = true;
            cv_.notify_one();
        }
 
        // wait until opened
        void knock() {
            std::unique_lock<std::mutex> lock(mutex_);
            cv_.wait(lock, [=] { return opened_; });
        }
 
        void close() {
            std::unique_lock<std::mutex> lock(mutex_);
            opened_ = false;
        }
 
        bool is_open() {
            return opened_;
        }
    private:
        std::mutex mutex_;
        std::condition_variable cv_;
        bool opened_;
    };
}