diff options
author | David Mazieres <dm@uun.org> | 2014-02-03 21:15:59 -0800 |
---|---|---|
committer | David Mazieres <dm@uun.org> | 2014-02-03 21:15:59 -0800 |
commit | 74cee7b410c46ec5d782fafbace055c72220fa95 (patch) | |
tree | 85d26100f53458f43d20c23dab00afdf3df37dc0 | |
parent | f8cf96a953c860601d5bc0aaa0060bd803493ea5 (diff) |
don't need mutex
-rw-r--r-- | chan.h | 41 | ||||
-rw-r--r-- | infinibuf.h | 3 |
2 files changed, 41 insertions, 3 deletions
@@ -0,0 +1,41 @@ +// -*- C++ -*- + +#include <cassert> +#include <condition_variable> +#include <exception> +#include <list> + +struct Chan_eof : std::exception { + const char *what() const noexcept override { return "EOF from Chan"; } +}; + +template<typename T> class Chan { + std::list<T> data_; + std::mutex m_; + std::condition_variable cv_; + bool eof_{false}; +public: + Chan() = default; + Chan(const Chan&) = delete; + template<class... Args> void write(Args&&... args) { + std::lock_guard<std::mutex> _lk (m_); + assert (!eof_); + data_.emplace_back(std::forward<Args>(args)...); + } + void writeeof() { + std::lock_guard<std::mutex> _lk (m_); + assert (!eof_); + eof_ = true; + } + T read() { + std::unique_lock<std::mutex> lk (m_); + while (data_.empty()) { + if (eof_) + throw Chan_eof(); + cv_.wait(lk); + } + T ret (std::move(data_.front())); + data_.pop_front(); + return ret; + } +}; diff --git a/infinibuf.h b/infinibuf.h index bf66dbc..ad96841 100644 --- a/infinibuf.h +++ b/infinibuf.h @@ -3,9 +3,6 @@ #include <condition_variable> #include <deque> #include <memory> -#include <mutex> - - /** \file infinibuf.h * \brief iostreams-friendly buffers that can grow without bounds. |