Skip to content

Instantly share code, notes, and snippets.

@subimage
Last active July 31, 2016 07:37
Show Gist options
  • Save subimage/4a7e5b0c0eee3cac8cb88b1461a30722 to your computer and use it in GitHub Desktop.
Save subimage/4a7e5b0c0eee3cac8cb88b1461a30722 to your computer and use it in GitHub Desktop.
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