Symbian platform (C++)
SDK native APIs, runtime and tooling
Loading...
Searching...
No Matches
channel.h
Go to the documentation of this file.
1// Copyright 2026 The Action Engine Authors and the Symbian SDK Authors.
2// Licensed under the Apache License, Version 2.0.
3// Guest adaptation of A11 cpp/thread/thread/channel.h at
4// fcccb8cb6e1e67d7ba0822ac14cece9ee4c7091b.
5
6#ifndef THREAD_FIBER_CHANNEL_H_
7#define THREAD_FIBER_CHANNEL_H_
8
9#include <cstddef>
10#include <cstdlib>
11#include <deque>
12#include <functional>
13#include <memory>
14#include <type_traits>
15#include <utility>
16
17#include <absl/base/nullability.h>
18
19#include "absl/container/inlined_vector.h"
20#include "thread/boost_primitives.h"
21#include "thread/fiber.h"
22#include "thread/select.h"
23
24namespace thread {
25
26template <typename T>
27requires std::is_move_assignable_v<T> class Channel;
28
29template <typename T>
30class Reader {
31 public:
32 Reader(const Reader&) = delete;
33 Reader& operator=(const Reader&) = delete;
34
35 bool Read(T* absl_nonnull out) { return channel_->Read(out); }
36
37 Case OnRead(T* absl_nonnull out, bool* absl_nonnull ok) {
38 return channel_->OnRead(out, ok);
39 }
40
41 private:
42 friend class Channel<T>;
43
44 explicit Reader(Channel<T>* absl_nonnull channel) : channel_(channel) {}
45
46 Channel<T>* absl_nonnull channel_;
47};
48
49template <typename T>
50class Writer {
51 public:
52 Writer(const Writer&) = delete;
53 Writer& operator=(const Writer&) = delete;
54
55 void Write(T&& item) { channel_->Write(std::move(item)); }
56
57 void Write(const T& item) { channel_->Write(item); }
58
59 Case OnWrite(T&& item) { return channel_->OnWrite(std::move(item)); }
60
61 Case OnWrite(const T& item) { return channel_->OnWrite(item); }
62
63 bool WriteUnlessCancelled(T&& item) {
64 return !thread::Cancelled() &&
65 Select({thread::OnCancel(), OnWrite(std::move(item))}) == 1;
66 }
67
68 bool WriteUnlessCancelled(const T& item) {
69 return !thread::Cancelled() &&
70 Select({thread::OnCancel(), OnWrite(item)}) == 1;
71 }
72
73 void Close() { channel_->Close(); }
74
75 private:
76 friend class Channel<T>;
77
78 explicit Writer(Channel<T>* absl_nonnull channel) : channel_(channel) {}
79
80 Channel<T>* absl_nonnull channel_;
81};
82
83// A11-compatible selectable buffered/rendezvous channel. Every transfer and
84// selection decision is made under the channel and selector locks. Wakes run
85// after those locks are released, so a ready fiber can reenter the channel.
86template <typename T>
87requires std::is_move_assignable_v<T> class Channel {
88 enum class Transfer { kCopy, kMove };
89 inline static constexpr Transfer kCopy = Transfer::kCopy;
90 inline static constexpr Transfer kMove = Transfer::kMove;
91
92 class ReadSelectable final : public internal::Selectable {
93 public:
94 explicit ReadSelectable(Channel* absl_nonnull channel)
95 : channel_(channel) {}
96
97 bool Handle(internal::CaseInSelectClause* absl_nonnull state,
98 bool enqueue) override {
99 return channel_->HandleRead(state, enqueue);
100 }
101
102 void Unregister(internal::CaseInSelectClause* absl_nonnull state) override {
103 channel_->Unregister(&channel_->readers_, state);
104 }
105
106 private:
107 Channel* absl_nonnull channel_;
108 };
109
110 class WriteSelectable final : public internal::Selectable {
111 public:
112 explicit WriteSelectable(Channel* absl_nonnull channel)
113 : channel_(channel) {}
114
115 bool Handle(internal::CaseInSelectClause* absl_nonnull state,
116 bool enqueue) override {
117 return channel_->HandleWrite(state, enqueue);
118 }
119
120 void Unregister(internal::CaseInSelectClause* absl_nonnull state) override {
121 channel_->Unregister(&channel_->writers_, state);
122 }
123
124 private:
125 Channel* absl_nonnull channel_;
126 };
127
128 public:
129 explicit Channel(std::size_t capacity)
130 : capacity_(capacity),
131 reader_(this),
132 read_selectable_(this),
133 writer_(this),
134 write_selectable_(this) {}
135
136 Channel(const Channel&) = delete;
137 Channel& operator=(const Channel&) = delete;
138
140 MutexLock lock(&mu_);
141 if (readers_ != nullptr || writers_ != nullptr) {
142 std::abort();
143 }
144 }
145
146 Reader<T>* absl_nonnull reader() { return &reader_; }
147
148 Writer<T>* absl_nonnull writer() { return &writer_; }
149
150 std::size_t length() const {
151 MutexLock lock(&mu_);
152 return queue_.size();
153 }
154
155 private:
156 friend class Reader<T>;
157 friend class Writer<T>;
158
159 bool Read(T* absl_nonnull out) {
160 bool ok = false;
161 Select({OnRead(out, &ok)});
162 return ok;
163 }
164
165 void Write(T&& item) { Select({OnWrite(std::move(item))}); }
166
167 void Write(const T& item) requires std::is_copy_constructible_v<T> {
168 Select({OnWrite(item)});
169 }
170
171 Case OnRead(T* absl_nonnull out, bool* absl_nonnull ok) {
172 return {&read_selectable_, out, ok};
173 }
174
175 Case OnWrite(T&& item) { return MakeWriteCase(&item, kMove); }
176
177 Case OnWrite(const T& item) requires std::is_copy_constructible_v<T> {
178 return MakeWriteCase(const_cast<T*>(&item), kCopy);
179 }
180
181 void Close() { CloseImpl(); }
182
183 using State = internal::CaseInSelectClause;
184 using Selector = internal::Selector;
185 using Wakes = absl::InlinedVector<std::shared_ptr<Selector>, 4>;
186
187 static T TransferItem(T* absl_nonnull item, Transfer strategy) {
188 if (strategy == kMove) {
189 return std::move(*item);
190 }
191 if constexpr (std::is_copy_constructible_v<T>) {
192 return *item;
193 }
194 std::abort();
195 }
196
197 static void Wake(Wakes* absl_nonnull wakes) {
198 for (const auto& selector : *wakes) {
199 selector->cv.Signal();
200 }
201 }
202
203 static void UnlinkIfQueued(State* absl_nullable* absl_nonnull head,
204 State* absl_nonnull state) {
205 if (state->prev != nullptr) {
206 internal::UnlinkFromList(head, state);
207 }
208 }
209
210 static bool LockPair(State* absl_nonnull first, State* absl_nonnull second) {
211 Selector* absl_nonnull left = first->selector.get();
212 Selector* absl_nonnull right = second->selector.get();
213 if (left == right) {
214 return false;
215 }
216 if (std::less<Selector*>{}(right, left)) {
217 std::swap(left, right);
218 }
219 left->mu.Lock();
220 right->mu.Lock();
221 if (left->picked_case_index == Selector::kNonePicked &&
222 right->picked_case_index == Selector::kNonePicked) {
223 return true;
224 }
225 right->mu.Unlock();
226 left->mu.Unlock();
227 return false;
228 }
229
230 static void UnlockPair(State* absl_nonnull first,
231 State* absl_nonnull second) {
232 first->selector->mu.Unlock();
233 second->selector->mu.Unlock();
234 }
235
236 static State* absl_nullable FindMatch(State* absl_nullable head,
237 State* absl_nonnull counterpart) {
238 if (head == nullptr) {
239 return nullptr;
240 }
241 State* absl_nullable current = head;
242 do {
243 if (LockPair(current, counterpart)) {
244 return current;
245 }
246 current = current->next;
247 } while (current != head);
248 return nullptr;
249 }
250
251 // Called with channel mu held. A queued writer can refill one freed buffer
252 // slot, including after the reader's immediate-case transfer.
253 void AdmitWriter(Wakes* absl_nonnull wakes) {
254 if (writers_ == nullptr || queue_.size() >= capacity_) {
255 return;
256 }
257 State* absl_nullable current = writers_;
258 do {
259 State* absl_nullable next = current->next;
260 MutexLock selector_lock(&current->selector->mu);
261 if (current->selector->picked_case_index == Selector::kNonePicked) {
262 T* absl_nonnull item = current->GetCase()->template GetArgPtr<T>(0);
263 Transfer strategy =
264 *current->GetCase()->template GetArgPtr<Transfer>(1);
265 queue_.push_back(TransferItem(item, strategy));
266 current->TryPick();
267 UnlinkIfQueued(&writers_, current);
268 wakes->push_back(current->selector);
269 return;
270 }
271 current = next;
272 } while (current != writers_ && writers_ != nullptr);
273 }
274
275 bool HandleRead(State* absl_nonnull reader, bool enqueue) {
276 Wakes wakes;
277 bool ready = false;
278 {
279 MutexLock lock(&mu_);
280 T* absl_nonnull out = reader->GetCase()->template GetArgPtr<T>(0);
281 bool* absl_nonnull ok = reader->GetCase()->template GetArgPtr<bool>(1);
282 if (!queue_.empty()) {
283 bool consumed = false;
284 {
285 MutexLock selector_lock(&reader->selector->mu);
286 if (reader->TryPick()) {
287 *out = std::move(queue_.front());
288 queue_.pop_front();
289 *ok = true;
290 consumed = true;
291 }
292 }
293 if (consumed) {
294 AdmitWriter(&wakes);
295 }
296 ready = true;
297 } else if (State* absl_nullable writer = FindMatch(writers_, reader)) {
298 T* absl_nonnull item = writer->GetCase()->template GetArgPtr<T>(0);
299 Transfer strategy = *writer->GetCase()->template GetArgPtr<Transfer>(1);
300 *out = TransferItem(item, strategy);
301 *ok = true;
302 reader->TryPick();
303 writer->TryPick();
304 UnlinkIfQueued(&writers_, writer);
305 wakes.push_back(writer->selector);
306 UnlockPair(writer, reader);
307 ready = true;
308 } else {
309 MutexLock selector_lock(&reader->selector->mu);
310 if (reader->selector->picked_case_index != Selector::kNonePicked) {
311 ready = true;
312 } else if (closed_) {
313 *ok = false;
314 reader->TryPick();
315 ready = true;
316 } else if (enqueue) {
317 internal::PushBack(&readers_, reader);
318 }
319 }
320 }
321 Wake(&wakes);
322 return ready;
323 }
324
325 bool HandleWrite(State* absl_nonnull writer, bool enqueue) {
326 Wakes wakes;
327 bool ready = false;
328 {
329 MutexLock lock(&mu_);
330 if (closed_) {
331 std::abort(); // A11's OnWrite on a closed channel is fatal.
332 }
333 State* absl_nullable reader =
334 closed_ ? nullptr : FindMatch(readers_, writer);
335 if (reader != nullptr) {
336 T* absl_nonnull item = writer->GetCase()->template GetArgPtr<T>(0);
337 Transfer strategy = *writer->GetCase()->template GetArgPtr<Transfer>(1);
338 T* absl_nonnull out = reader->GetCase()->template GetArgPtr<T>(0);
339 bool* absl_nonnull ok = reader->GetCase()->template GetArgPtr<bool>(1);
340 *out = TransferItem(item, strategy);
341 *ok = true;
342 reader->TryPick();
343 writer->TryPick();
344 UnlinkIfQueued(&readers_, reader);
345 wakes.push_back(reader->selector);
346 UnlockPair(reader, writer);
347 ready = true;
348 } else {
349 MutexLock selector_lock(&writer->selector->mu);
350 if (writer->selector->picked_case_index != Selector::kNonePicked) {
351 ready = true;
352 } else if (queue_.size() < capacity_) {
353 T* absl_nonnull item = writer->GetCase()->template GetArgPtr<T>(0);
354 Transfer strategy =
355 *writer->GetCase()->template GetArgPtr<Transfer>(1);
356 queue_.push_back(TransferItem(item, strategy));
357 writer->TryPick();
358 ready = true;
359 } else if (enqueue) {
360 internal::PushBack(&writers_, writer);
361 }
362 }
363 }
364 Wake(&wakes);
365 return ready;
366 }
367
368 void Unregister(State* absl_nullable* absl_nonnull head,
369 State* absl_nonnull state) {
370 MutexLock lock(&mu_);
371 UnlinkIfQueued(head, state);
372 }
373
374 Case MakeWriteCase(T* absl_nonnull item, Transfer strategy) {
375 Case result(&write_selectable_);
376 result.AddArg(item);
377 result.AddArg(strategy == kCopy ? &kCopy : &kMove);
378 return result;
379 }
380
381 void CloseImpl() {
382 Wakes wakes;
383 {
384 MutexLock lock(&mu_);
385 if (closed_ || writers_ != nullptr) {
386 std::abort();
387 }
388 closed_ = true;
389 while (readers_ != nullptr) {
390 State* absl_nullable state = readers_;
391 {
392 MutexLock selector_lock(&state->selector->mu);
393 if (state->TryPick()) {
394 *state->GetCase()->template GetArgPtr<bool>(1) = false;
395 wakes.push_back(state->selector);
396 }
397 internal::UnlinkFromList(&readers_, state);
398 }
399 }
400 }
401 Wake(&wakes);
402 }
403
404 const std::size_t capacity_;
405 mutable Mutex mu_;
406 std::deque<T> queue_;
407 bool closed_ = false;
408 State* absl_nullable readers_ = nullptr;
409 State* absl_nullable writers_ = nullptr;
410 Reader<T> reader_;
411 ReadSelectable read_selectable_;
412 Writer<T> writer_;
413 WriteSelectable write_selectable_;
414};
415
416} // namespace thread
417
418#endif // THREAD_FIBER_CHANNEL_H_
int first
Definition frame.cc:152
int second
Definition frame.cc:153
A Channel is a bounded FIFO queue that allows multiple readers and writers to communicate with each o...
Definition channel.h:87
Writer< T > *absl_nonnull writer()
Definition channel.h:148
friend class Writer< T >
Definition channel.h:349
Channel & operator=(const Channel &)=delete
~Channel()
Definition channel.h:139
friend class Reader< T >
Definition channel.h:348
Channel(std::size_t capacity)
Definition channel.h:129
Reader< T > *absl_nonnull reader()
Definition channel.h:146
std::size_t length() const
Definition channel.h:150
Channel(const Channel &)=delete
Definition boost_primitives.h:97
A Reader is used to read items from a Channel.
Definition channel.h:95
Case OnRead(T *absl_nonnull out, bool *absl_nonnull ok)
Definition channel.h:37
bool Read(T *absl_nonnull out)
Definition channel.h:35
friend class Channel< T >
Definition channel.h:145
Reader(const Reader &)=delete
Reader & operator=(const Reader &)=delete
A Writer is used to write items to a Channel.
Definition channel.h:161
Case OnWrite(T &&item)
Definition channel.h:59
friend class Channel< T >
Definition channel.h:272
Writer(const Writer &)=delete
void Close()
Definition channel.h:73
Case OnWrite(const T &item)
Definition channel.h:61
Writer & operator=(const Writer &)=delete
bool WriteUnlessCancelled(const T &item)
Definition channel.h:68
void Write(T &&item)
Definition channel.h:55
void Write(const T &item)
Definition channel.h:57
bool WriteUnlessCancelled(T &&item)
Definition channel.h:63
void UnlinkFromList(CaseInSelectClause *absl_nullable *absl_nullable head, CaseInSelectClause *absl_nonnull element)
Definition cases.h:155
void PushBack(CaseInSelectClause *absl_nullable *absl_nullable head, CaseInSelectClause *absl_nonnull element)
Definition cases.h:138
Definition channel.h:29
bool Cancelled()
Definition fiber.cc:291
Case OnCancel()
Definition fiber.cc:296
int Select(const CaseArray &cases)
Returns the index of the first case that is ready, blocking until one is.
Definition select.h:18
A Case represents a selectable case in a Select statement.
Definition cases.h:57
uint8_t out
Definition usb.cc:198