Раздел «Язык Ruby».ThreadingSnippets:

Threading code snippets

a = []
n = 10
adder   = Thread.new { loop { a << rand(n) } }
adder2  = Thread.new { loop { a.unshift rand(n) } }
remover = Thread.new { loop { a.delete rand(n) } }
printer = Thread.new { loop { sleep 1; puts a.inspect; STDOUT.flush} }

loop do
  # Is Array thread safe?
  # Interpreter does not crash but still integrity is not garanteed
  # Is there any memory leaks?
  break unless [adder,adder2,remover,printer].all?{|t| t.alive? }
end

a = []
n = 10
adder   = Thread.new { loop { a << rand(n) } }
adder2  = Thread.new { loop { a.unshift rand(n) } }
remover = Thread.new { loop { a.delete rand(n) } }
printer = Thread.new { loop { sleep 1; puts a.inspect; STDOUT.flush} }

sleep 3
# there is the main thread. It's me.
# Main thread kills others when exits.

th = Thread.new { nil.hello_cruel_world } 
sleep 1

puts "Am i alive? My friend '#{th}' is #{th.alive? ? 'alive' : 'dead'}."

th.join

puts "Now i am definitely not alive. My dead friend killed me when i joined him to myself. You can't see this printed."

sleep 2

def initialize
   @lock = Mutex.new
   @subscriptions = Hash.new { |h,k| h[k] = [].freeze }
 end

 def publish(publisher, message)
   @lock.synchronize do
     @subscriptions[publisher]
   end.each do |subscriber|
     subscriber.deliver message
   end
   self
 end

 def subscribe(subscriber, publisher)
   @lock.synchronize do
     subscriptions = @subscriptions[publisher].dup
     subscriptions.push subscriber
     @subscriptions[publisher] = subscriptions.freeze
   end
   self
 end

 def unsubscribe(subscriber, publisher)
   @lock.synchronize do
     subscriptions = @subscriptions[publisher].dup
     subscriptions.delete subscriber
     @subscriptions[publisher] = subscriptions.freeze
   end
   self
 end