-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
Copy pathchannel.cr
506 lines (416 loc) · 11.7 KB
/
channel.cr
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
require "fiber"
require "crystal/spin_lock"
require "crystal/pointer_linked_list"
require "channel/select"
# A `Channel` enables concurrent communication between fibers.
#
# They allow communicating data between fibers without sharing memory and without having to worry about locks, semaphores or other special structures.
#
# ```
# channel = Channel(Int32).new
#
# spawn do
# channel.send(0)
# channel.send(1)
# end
#
# channel.receive # => 0
# channel.receive # => 1
# ```
#
# NOTE: Although a `Channel(Nil)` or any other nilable types like `Channel(Int32?)` are valid
# they are discouraged since from certain methods or constructs it receiving a `nil` as data
# will be indistinguishable from a closed channel.
#
class Channel(T)
@lock = Crystal::SpinLock.new
@queue : Deque(T)?
# :nodoc:
record UseDefault
class ClosedError < Exception
def initialize(msg = "Channel is closed")
super(msg)
end
end
private module SenderReceiverCloseAction
def close
self.state = DeliveryState::Closed
_select_context = self.select_context
if _select_context.nil? || _select_context.try_trigger
self.fiber.enqueue
end
end
end
private struct Sender(T)
include Crystal::PointerLinkedList::Node
include SenderReceiverCloseAction
property fiber : Fiber
property data : T
property state : DeliveryState
property select_context : SelectContext(Nil)?
def initialize
@fiber = uninitialized Fiber
@data = uninitialized T
@state = DeliveryState::None
end
end
private struct Receiver(T)
include Crystal::PointerLinkedList::Node
include SenderReceiverCloseAction
property fiber : Fiber
property data : T
property state : DeliveryState
property select_context : SelectContext(T)?
def initialize
@fiber = uninitialized Fiber
@data = uninitialized T
@state = DeliveryState::None
end
end
def initialize(@capacity = 0)
@closed = false
@senders = Crystal::PointerLinkedList(Sender(T)).new
@receivers = Crystal::PointerLinkedList(Receiver(T)).new
if capacity > 0
@queue = Deque(T).new(capacity)
end
end
# Closes the channel.
# The method prevents any new value from being sent to / received from the channel.
# All fibers blocked in `send` or `receive` will be awakened with `Channel::ClosedError`
#
# Both awaiting and subsequent calls to `#send` will consider the channel closed.
# All items successfully sent to the channel can be received, before `#receive` considers the channel closed.
# Calling `#close` on a closed channel does not have any effect.
#
# It returns `true` when the channel was successfully closed, or `false` if it was already closed.
def close : Bool
sender_list = Crystal::PointerLinkedList(Sender(T)).new
receiver_list = Crystal::PointerLinkedList(Receiver(T)).new
@lock.sync do
return false if @closed
@closed = true
@senders, sender_list = sender_list, @senders
@receivers, receiver_list = receiver_list, @receivers
end
sender_list.each(&.value.close)
receiver_list.each(&.value.close)
true
end
def closed? : Bool
@closed
end
# Sends a value to the channel.
# If the channel has spare capacity, then the method returns immediately.
# Otherwise, this method blocks the calling fiber until another fiber calls `#receive` on the channel.
#
# Raises `ClosedError` if the channel is closed or closes while waiting on a full channel.
def send(value : T) : self
sender = Sender(T).new
@lock.lock
case send_internal(value)
in .delivered?
@lock.unlock
in .closed?
@lock.unlock
raise ClosedError.new
in .none?
sender.fiber = Fiber.current
sender.data = value
@senders.push pointerof(sender)
@lock.unlock
Fiber.suspend
case sender.state
in .delivered?
# ignore
in .closed?
raise ClosedError.new
in .none?
raise "BUG: Fiber was awaken without channel delivery state set"
end
end
self
end
protected def send_internal(value : T)
if @closed
DeliveryState::Closed
elsif receiver_ptr = dequeue_receiver
receiver_ptr.value.data = value
receiver_ptr.value.state = DeliveryState::Delivered
receiver_ptr.value.fiber.enqueue
DeliveryState::Delivered
elsif (queue = @queue) && queue.size < @capacity
queue << value
DeliveryState::Delivered
else
DeliveryState::None
end
end
# Receives a value from the channel.
# If there is a value waiting, then it is returned immediately. Otherwise, this method blocks until a value is sent to the channel.
#
# Raises `ClosedError` if the channel is closed or closes while waiting for receive.
#
# ```
# channel = Channel(Int32).new
# spawn do
# channel.send(1)
# end
# channel.receive # => 1
# ```
def receive : T
receive_impl { raise ClosedError.new }
end
# Receives a value from the channel.
# If there is a value waiting, it is returned immediately. Otherwise, this method blocks until a value is sent to the channel.
#
# Returns `nil` if the channel is closed or closes while waiting for receive.
def receive? : T?
receive_impl { return nil }
end
private def receive_impl(&)
receiver = Receiver(T).new
@lock.lock
state, value = receive_internal
case state
in .delivered?
@lock.unlock
raise "BUG: Unexpected UseDefault value for delivered receive" if value.is_a?(UseDefault)
value
in .closed?
@lock.unlock
yield
in .none?
receiver.fiber = Fiber.current
@receivers.push pointerof(receiver)
@lock.unlock
Fiber.suspend
case receiver.state
in .delivered?
receiver.data
in .closed?
yield
in .none?
raise "BUG: Fiber was awaken without channel delivery state set"
end
end
end
protected def receive_internal
if (queue = @queue) && !queue.empty?
deque_value = queue.shift
if sender_ptr = dequeue_sender
queue << sender_ptr.value.data
sender_ptr.value.state = DeliveryState::Delivered
sender_ptr.value.fiber.enqueue
end
{DeliveryState::Delivered, deque_value}
elsif sender_ptr = dequeue_sender
value = sender_ptr.value.data
sender_ptr.value.state = DeliveryState::Delivered
sender_ptr.value.fiber.enqueue
{DeliveryState::Delivered, value}
elsif @closed
{DeliveryState::Closed, UseDefault.new}
else
{DeliveryState::None, UseDefault.new}
end
end
private def dequeue_receiver
while receiver_ptr = @receivers.shift?
select_context = receiver_ptr.value.select_context
if select_context && !select_context.try_trigger
receiver_ptr.value.state = DeliveryState::Delivered
next
end
break
end
receiver_ptr
end
private def dequeue_sender
while sender_ptr = @senders.shift?
select_context = sender_ptr.value.select_context
if select_context && !select_context.try_trigger
sender_ptr.value.state = DeliveryState::Delivered
next
end
break
end
sender_ptr
end
def inspect(io : IO) : Nil
to_s(io)
end
def pretty_print(pp)
pp.text inspect
end
def self.receive_first(*channels)
receive_first channels
end
def self.receive_first(channels : Enumerable(Channel))
_, value = self.select(channels.map(&.receive_select_action))
value
end
def self.send_first(value, *channels) : Nil
send_first value, channels
end
def self.send_first(value, channels : Enumerable(Channel)) : Nil
self.select(channels.map(&.send_select_action(value)))
nil
end
# :nodoc:
def send_select_action(value : T)
SendAction.new(self, value)
end
# :nodoc:
def receive_select_action
StrictReceiveAction.new(self)
end
# :nodoc:
def receive_select_action?
LooseReceiveAction.new(self)
end
private class StrictReceiveAction(T)
include SelectAction(T)
property receiver : Receiver(T)
def initialize(@channel : Channel(T))
@receiver = Receiver(T).new
end
def execute : DeliveryState
state, value = @channel.receive_internal
if state.delivered?
@receiver.data = value.as(T)
end
state
end
def result : T
@receiver.data
end
def wait(context : SelectContext(T)) : Nil
@receiver.fiber = Fiber.current
@receiver.select_context = context
@channel.@receivers.push pointerof(@receiver)
end
def wait_result_impl(context : SelectContext(T))
case @receiver.state
in .delivered?
context.action.result
in .closed?
raise ClosedError.new
in .none?
raise "BUG: StrictReceiveAction.wait_result_impl called with DeliveryState::None"
end
end
def unwait_impl(context : SelectContext(T))
if !@channel.closed? && @receiver.state.none?
@channel.@receivers.delete pointerof(@receiver)
end
end
def lock_object_id : UInt64
@channel.object_id
end
def lock : Nil
@channel.@lock.lock
end
def unlock : Nil
@channel.@lock.unlock
end
def default_result
raise ClosedError.new
end
end
private class LooseReceiveAction(T)
include SelectAction(T)
property receiver : Receiver(T)
def initialize(@channel : Channel(T))
@receiver = Receiver(T).new
end
def execute : DeliveryState
state, value = @channel.receive_internal
if state.delivered?
@receiver.data = value.as(T)
end
state
end
def result : T
@receiver.data
end
def wait(context : SelectContext(T)) : Nil
@receiver.fiber = Fiber.current
@receiver.select_context = context
@channel.@receivers.push pointerof(@receiver)
end
def wait_result_impl(context : SelectContext(T))
case @receiver.state
in .delivered?
context.action.result
in .closed?
nil
in .none?
raise "BUG: LooseReceiveAction.wait_result_impl called with DeliveryState::None"
end
end
def unwait_impl(context : SelectContext(T))
if !@channel.closed? && @receiver.state.none?
@channel.@receivers.delete pointerof(@receiver)
end
end
def lock_object_id : UInt64
@channel.object_id
end
def lock : Nil
@channel.@lock.lock
end
def unlock : Nil
@channel.@lock.unlock
end
def default_result
nil
end
end
private class SendAction(T)
include SelectAction(Nil)
property sender : Sender(T)
def initialize(@channel : Channel(T), value : T)
@sender = Sender(T).new
@sender.data = value
end
def execute : DeliveryState
@channel.send_internal(@sender.data)
end
def result : Nil
nil
end
def wait(context : SelectContext(Nil)) : Nil
@sender.fiber = Fiber.current
@sender.select_context = context
@channel.@senders.push pointerof(@sender)
end
def wait_result_impl(context : SelectContext(Nil))
case @sender.state
in .delivered?
context.action.result
in .closed?
raise ClosedError.new
in .none?
raise "BUG: SendAction.wait_result_impl called with DeliveryState::None"
end
end
def unwait_impl(context : SelectContext(Nil))
if !@channel.closed? && @sender.state.none?
@channel.@senders.delete pointerof(@sender)
end
end
def lock_object_id : UInt64
@channel.object_id
end
def lock : Nil
@channel.@lock.lock
end
def unlock : Nil
@channel.@lock.unlock
end
def default_result
raise ClosedError.new
end
end
end