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:
```ruby hello = concurrently do wait 0.2 # seconds “hello” end
world = concurrently do wait 0.1 # seconds “world” end
puts “#hellohello.await_result #worldworld.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:
- an elapsed time period (Kernel#wait),
- readability and writability of IO (IO#await_readable, IO#await_writable) and
- the result of another evaluation (Concurrently::Proc::Evaluation#await_result).
Since evaluations run independently they are not blocking other evaluations while waiting.
This is a little server reading from an IO and printing the received messages:
```ruby # Let’s start with creating a pipe to connect client and server r,w = IO.pipe
# We let the server code run concurrently so it runs independently. It reads # from the pipe non-blocking and awaits readability if the pipe is not readable. concurrently do while true begin puts r.read_nonblock 32 rescue IO::WaitReadable r.await_readable retry end end end
# The client writes to the pipe every 0.5 seconds 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)
Supported Ruby Versions
- Ruby 2.2.7+
- mruby 1.3+
Copyright 2016-present Christopher Aue
Concurrently is licensed under the Apache License, Version 2.0. Please see the file called LICENSE.