Skip to content

Instantly share code, notes, and snippets.

@rklemme
Created January 4, 2011 08:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rklemme/764540 to your computer and use it in GitHub Desktop.
Save rklemme/764540 to your computer and use it in GitHub Desktop.
Sample answer for thread "Threading in ruby"
require 'thread'
# explicit type for items that we process here
Item = Struct.new :name, :sha1, :meta
# dummies
def sha1(x) x.hash end
def update_metadata(it) it.meta = Time.now end
#
# main
#
files = [Item["f1"], Item["f2"], Item["f3"]]
queue = Queue.new
updater = Thread.new do
until (item = queue.deq).nil?
update_metadata(item)
p item # debug
end
end
# no extra thread needed
files.each do |f|
f.sha1 = sha1(f.name)
queue.enq f
end
# indicate termination
queue.enq nil
# graceful shutdown
updater.join
require 'thread'
# explicit type for items that we process here
Item = Struct.new :name, :sha1, :meta
# dummies
def sha1(x) x.hash end
def update_metadata(it) it.meta = Time.now end
#
# main
#
files = [Item["f1"], Item["f2"], Item["f3"]]
index = -1
mutex = Mutex.new
available = ConditionVariable.new
updater = Thread.new do
files.size.times do |i|
mutex.synchronize do
while i > index
available.wait(mutex)
end
end
item = files[i]
update_metadata(item)
p item # debug
end
end
# no extra thread needed
files.each_with_index do |f, i|
f.sha1 = sha1(f.name)
mutex.synchronize do
index = i
available.signal
end
end
# graceful shutdown
updater.join
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment