views:

69

answers:

1

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 :)

+1  A: 

You need a shared thread variable that indicates whether a thread has found the answer and is accessed by the threads via a Mutex.

Farrel
D'oh of course! :) Thanks a lot!
parasquid
Alternatively, the main thread could block on this shared variable (commonly called a "condition variable" or a "condvar") instead of `join`-ing all the threads. When it sees the variable set, it sends a `Thread.kill` command to all of the worker threads. This approach may be better if you intend on re-using the worker threads (send a `Thread.stop` instead of a `kill` and then later use `Thread.wakeup` to revive it again).
bta