-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathbuffers.rb
More file actions
69 lines (56 loc) · 1.22 KB
/
buffers.rb
File metadata and controls
69 lines (56 loc) · 1.22 KB
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
# frozen_string_literal: true
require_relative "../lib/goru"
channel = Goru::Channel.new(size: 3)
class Reader
include Goru
def initialize(channel:)
@received = []
go(:sleep, channel: channel, intent: :r) { |routine|
case routine.state
when :sleep
routine.update(:read)
routine.sleep(rand)
when :read
if (value = routine.read)
@received << value
puts "received: #{value}"
routine.update(:sleep)
else
routine.finished
end
end
}
end
attr_reader :received
end
class Writer
include Goru
def initialize(channel:)
@writable = 10.times.to_a
values = @writable.dup
go(channel: channel, intent: :w) { |routine|
if (value = values.shift)
routine << value
puts "wrote: #{value}"
else
channel.close
routine.finished
end
}
end
attr_reader :writable
end
reader = Reader.new(channel: channel)
writer = Writer.new(channel: channel)
start = Time.now
loop do
if reader.received == writer.writable
break
elsif Time.now - start > 5
fail "timed out"
else
sleep(0.1)
end
end
puts "all received after #{Time.now - start}"
Goru::Scheduler.stop