Skip to content

Instantly share code, notes, and snippets.

@subimage
Last active Jul 31, 2016
Embed
What would you like to do?
A threaded counter implementation in Ruby
#!/usr/bin/env ruby
require 'singleton'
require 'thread'
# Test to see if I remember how to use threads in Ruby properly
class ThreadCounter
include Singleton
NUM_THREADS = 4
def initialize
@count = 0
@mutex = Mutex.new
@threads = []
end
def run
(1..NUM_THREADS).each do |i|
@threads << Thread.new { count_forever(i) }
end
@threads.each { |t| t.join }
# For ctrl-c support
rescue SystemExit, Interrupt
puts "Caught CTRL-C WE OUT"
Thread.list.each { |t| Thread.kill(t) }
return
end
def count_forever(thread_num)
while true do
sleep(rand*10)
@mutex.synchronize { @count += 1 }
puts "Thread #{thread_num}: #{@count}"
end
end
end
ThreadCounter.instance.run
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment