Created
January 4, 2011 08:31
-
-
Save rklemme/764540 to your computer and use it in GitHub Desktop.
Sample answer for thread "Threading in ruby"
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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