Chops Net IP
Loading...
Searching...
No Matches
io_common.hpp
Go to the documentation of this file.
1
23#ifndef IO_COMMON_HPP_INCLUDED
24#define IO_COMMON_HPP_INCLUDED
25
26#include <optional>
27#include <mutex>
28
31
32namespace chops {
33namespace net {
34namespace detail {
35
36template <typename E>
37class io_common {
38private:
39 bool m_io_started; // original implementation this was std::atomic_bool
40 bool m_write_in_progress;
41 output_queue<E> m_outq;
42 mutable std::mutex m_mutex;
43
44private:
45 using lk_guard = std::lock_guard<std::mutex>;
46
47private:
48 void do_clear() { // mutex should already be locked
49 m_outq.clear();
50 m_write_in_progress = false;
51 }
52
53public:
54 enum write_status { io_stopped, queued, write_started };
55
56public:
57
58 io_common() noexcept :
59 m_io_started(false), m_write_in_progress(false), m_outq(), m_mutex() { }
60
61 // the following four methods can be called concurrently
62 auto get_output_queue_stats() const noexcept {
63 lk_guard lg(m_mutex);
64 return m_outq.get_queue_stats();
65 }
66
67 bool is_io_started() const noexcept {
68 lk_guard lg(m_mutex);
69 return m_io_started;
70 }
71
72 bool set_io_started() noexcept {
73 lk_guard lg(m_mutex);
74 return m_io_started ? false : (m_io_started = true, true);
75 }
76
77 bool set_io_stopped() noexcept {
78 lk_guard lg(m_mutex);
79 return m_io_started ? (m_io_started = false, true) : false;
80 }
81
82 // rest of these method called only from within run thread
83 bool is_write_in_progress() const noexcept {
84 lk_guard lg(m_mutex);
85 return m_write_in_progress;
86 }
87
88 void clear() noexcept {
89 lk_guard lg(m_mutex);
90 do_clear();
91 }
92
93 // func is the code that performs actual write, typically async_write or
94 // async_sendto
95 template <typename F>
96 write_status start_write(const E& elem, F&& func) {
97 lk_guard lg(m_mutex);
98 if (!m_io_started) {
99 do_clear();
100 return io_stopped; // shutdown happening or not io_started, don't start a write
101 }
102 if (m_write_in_progress) { // queue buffer
103 m_outq.add_element(elem);
104 return queued;
105 }
106 m_write_in_progress = true;
107 func(elem);
108 return write_started;
109 }
110
111 template <typename F>
112 void write_next_elem(F&& func) {
113 lk_guard lg(m_mutex);
114 if (!m_io_started) { // shutting down
115 do_clear();
116 return;
117 }
118 auto elem = m_outq.get_next_element();
119 if (!elem) {
120 m_write_in_progress = false;
121 return;
122 }
123 m_write_in_progress = true;
124 func(*elem);
125 return;
126 }
127
128};
129
130} // end detail namespace
131} // end net namespace
132} // end chops namespace
133
134#endif
135
Definition io_common.hpp:37
Definition output_queue.hpp:40
Utility class to manage output data queueing.
Structures containing statistics gathered on internal queues.