Skip to content

Instantly share code, notes, and snippets.

@kingsleyh
Last active April 27, 2020 14:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kingsleyh/4f50ba826238c41519c9ff47374b9d64 to your computer and use it in GitHub Desktop.
Save kingsleyh/4f50ba826238c41519c9ff47374b9d64 to your computer and use it in GitHub Desktop.
multi fiber jobs
class Job
def self.create(number_of_jobs : Int32) : Array(Job)
jobs = [] of Job
inbound = Channel(String).new
outbound = Channel(String).new
number_of_jobs.times do |_|
job = Job.new(inbound, outbound)
job.run
jobs << job
end
jobs
end
@message_pool = [] of String
def initialize(@inbound : Channel(String), @outbound : Channel(String))
end
def task(message : String)
response("#{message}-ok")
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
end
jobs = Job.create(10)
jobs.each_with_index do |w, i|
w.exec(i.to_s)
end
jobs.each do |w|
puts w.receive
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment