1. 程式人生 > >[N周N語言] C++ Go-Style Channel

[N周N語言] C++ Go-Style Channel

#include <mutex>
#include <atomic>
#include <queue>
#include <exception>

template<class T>
class channel {
public:
    void put(const T &x) {
        std::unique_lock<std::mutex> lock(mutex);
        if (closed)
            throw std::logic_error("Put to Closed Channel");
        queue.push_back(x);
        cond.notify_one();
    }

    bool get(T &out, bool wait = true) {
        std::unique_lock<std::mutex> lock(mutex);
        if (wait)
            cond.wait(lock, [&](){ return closed || !queue.empty(); });
        if (queue.empty())
            return false;
        out = queue.front();
        queue.pop_front();
        return true;
    }

    bool IsClosed() {
        std::unique_lock<std::mutex> lock(mutex);
        return closed;
    }

    void close() {
        std::unique_lock<std::mutex> lock(mutex);
        closed = true;
        cond.notify_all();
    }

private:
    bool closed;
    std::queue<T> queue;
    std::mutex mutex;
    std::condition_variable cond;
};