/
multi_process.cr
62 lines (50 loc) · 1.19 KB
/
multi_process.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
module ::Sushi::Core::MultiProcess
abstract class Worker
abstract def task(message : String)
def self.create(number_of_workers : Int32) : Array(Worker)
workers = [] of Worker
inbound = Channel(String).new
outbound = Channel(String).new
number_of_workers.times do |_|
worker = new(inbound, outbound)
worker.run
workers << worker
end
workers
end
@message_pool = [] of String
def initialize(@inbound : Channel(String), @outbound : Channel(String))
end
def run
spawn do
loop do
next unless message = @inbound.receive
task(message)
end
end
wait_fiber
end
def wait_fiber
spawn do
loop do
sleep 0.01
next unless message = @message_pool.shift?
@inbound.send(message)
end
end
end
def exec(message : String? = nil)
@message_pool << message
end
def response(message : String)
@outbound.send(message)
end
def receive : String?
return nil unless message = @outbound.receive
message
end
def kill
# no idea how to stop the Fiber
end
end
end