C++ Channel
Loading...
Searching...
No Matches
blocking_iterator.hpp
1// Copyright (C) 2020-2025 Andrei Avram
2
3#ifndef MSD_CHANNEL_BLOCKING_ITERATOR_HPP_
4#define MSD_CHANNEL_BLOCKING_ITERATOR_HPP_
5
6#include <cstddef>
7#include <iterator>
8#include <mutex>
9
10namespace msd {
11
19template <typename Channel>
21 public:
25 using value_type = typename Channel::value_type;
26
30 using reference = const typename Channel::value_type&;
31
35 using iterator_category = std::input_iterator_tag;
36
40 using difference_type = std::ptrdiff_t;
41
45 using pointer = const value_type*;
46
52 explicit blocking_iterator(Channel& chan) : chan_{chan} {}
53
59 blocking_iterator<Channel> operator++() const noexcept { return *this; }
60
67 {
68 chan_ >> value_;
69
70 return value_;
71 }
72
80 {
81 std::unique_lock<std::mutex> lock{chan_.mtx_};
82 chan_.waitBeforeRead(lock);
83
84 return !(chan_.closed() && chan_.empty());
85 }
86
87 private:
88 Channel& chan_;
89 value_type value_{};
90};
91
92} // namespace msd
93
94#endif // MSD_CHANNEL_BLOCKING_ITERATOR_HPP_
An iterator that block the current thread, waiting to fetch elements from the channel.
Definition blocking_iterator.hpp:20
std::ptrdiff_t difference_type
Signed integral type for iterator difference.
Definition blocking_iterator.hpp:40
reference operator*()
Retrieves and returns the next element from the channel.
Definition blocking_iterator.hpp:66
blocking_iterator< Channel > operator++() const noexcept
Advances the iterator to the next element.
Definition blocking_iterator.hpp:59
blocking_iterator(Channel &chan)
Constructs a blocking iterator from a channel reference.
Definition blocking_iterator.hpp:52
const value_type * pointer
Pointer type to the value_type.
Definition blocking_iterator.hpp:45
bool operator!=(blocking_iterator< Channel >) const
Makes iteration continue until the channel is closed and empty.
Definition blocking_iterator.hpp:79
const typename Channel::value_type & reference
Constant reference to the type of the elements stored in the channel.
Definition blocking_iterator.hpp:30
std::input_iterator_tag iterator_category
Supporting single-pass reading of elements.
Definition blocking_iterator.hpp:35
typename Channel::value_type value_type
The type of the elements stored in the channel.
Definition blocking_iterator.hpp:25