A lightweight Ruby concurrency system with multi-thread and multi-process support with Pipes and Channels.
Go.rb is inspired by the 'Go' programming language. 'Go' excels in concurrency, so I decided to recreate some of these features in Ruby. This includes easy creation and management of Threads and Process-Forking. Channels allow communication across Threads and Pipes allow for data interchange across Processes.
Getting started with Go.rb is very simple. First, install the Gem:
gem install Go.rb
or, in your gem file:
gem 'Go.rb'
Using the gem is very simple. Here are a few examples:
require 'go'
go { puts "Hello World" }
go { puts "Goodbye World" }
# => "Hello World"
# => "Goodbye World"
In the above case, both "Hello World" and "Goodbye World" are executed in their own, individual threads.
require 'go'
go do
sleep 1
puts "Hello World"
end
go { puts "Goodbye World" }
# => "Goodbye World"
# => "Hello World"
Additionally, Multiple Processes are supported.
require 'go'
gofork { puts "Hello from another Process" }
gofork { sleep 1 }.wait
# => "Hello from another Process"
# => *waits 1 second before exiting*
For communication across Threads, a Channels system is implemented. Channels can hold any object
require 'go'
channel = gochan # Create a new Channel
go(channel) { |chan| chan << "Hello World" }
puts channel.get
# => "Hello World"
channel << "Hi Earth"
channel2 = gochan
go(channel, channel2) { |chan, chan2| chan2 << chan.get }
puts channel2.get
# => "Hi Earth"
For communication across Processes, a Pipes system is implemented. Objects can not be transferred across processes, only byte streams like binary strings.
require 'go'
pipe = gopipe
gofork(pipe) { |pipe| pipe << "Hello" }
puts pipe.read(5)
# => "Hello"
pipe.puts "Hello World"
gofork(pipe) { |pipe| puts pipe.gets }
# => "Hello World"
pipe.close