Concurrently
Concurrently is a concurrency framework for Ruby and mruby built upon
fibers. With it code can be evaluated independently in its own execution
context similar to a thread. Execution contexts are called evaluations in
Concurrently and are created with Kernel#concurrently:
hello = concurrently do
wait 0.2
"hello"
end
world = concurrently do
wait 0.1
"world"
end
puts "#{hello.await_result} #{world.await_result}"
In this example we have three evaluations: The root evaluation and two more
concurrent evaluations started by said root evaluation. The root evaluation
waits until both concurrent evaluations were concluded and then prints "hello
world".
Synchronization with events
Evaluations can be synchronized with certain events by waiting for them. These
events are:
Since evaluations run independently they are not blocking other evaluations
while waiting.
Concurrent I/O
When doing I/O it is important to do it non-blocking. If the IO object is
not ready use IO#await_readable and IO#await_writable to await
readiness.
For more about non-blocking I/O, see the core ruby docs for
IO#read_nonblock and IO#write_nonblock.
This is a little server reading from an IO and printing the received messages:
r,w = IO.pipe
concurrently do
while true
begin
puts r.read_nonblock 32
rescue IO::WaitReadable
r.await_readable
retry
end
end
end
puts "#{Time.now.strftime('%H:%M:%S.%L')} (Start time)"
while true
wait 0.5
w.write Time.now.strftime('%H:%M:%S.%L')
end
The root evaluation is effectively blocked by waiting or writing messages.
But since the server runs concurrently it is not affected by this and happily
prints its received messages.
This is the output:
23:20:42.357 (Start time)
23:20:42.858
23:20:43.359
23:20:43.860
23:20:44.360
...
Documentation
Supported Ruby Versions
Development
Release Notes
License
Copyright 2016-present Christopher Aue
Concurrently is licensed under the Apache License, Version 2.0. Please see the
file called LICENSE.