Here is a sample program:
def worker(from, to)
puts "#{from}..#{to}"
for i in from..to do
if i == 42
puts "kill the rest of the threads"
break;
end
puts i
sleep 1
end
end
if __FILE__ == $0
threads = []
for i in 0..9 do
threads << Thread.new { worker(i*10, i*10+10) }
end
threads.each { |thread| thread.join }
end
I'd like all the threads to stop when one of the threads found the answer (in this case, 42). I'm not sure what this concept is called, which is why I'm unable to search for it.
I appreciate the help :)
You need a shared thread variable that indicates whether a thread has found the answer and is accessed by the threads via a Mutex.