2 # thwait.rb - thread synchronization class
3 # $Release Version: 0.9 $
5 # $Date: 2002/02/01 06:36:19 $
6 # by Keiju ISHITSUKA(Nihpon Rational Software Co.,Ltd.)
10 # provides synchronization for multiple threads.
13 # * ThreadsWait.all_waits(thread1,...)
14 # waits until all of specified threads are terminated.
15 # if a block is supplied for the method, evaluates it for
16 # each thread termination.
17 # * th = ThreadsWait.new(thread1,...)
18 # creates synchronization object, specifying thread(s) to wait.
22 # list threads to be synchronized
24 # is there any thread to be synchronized.
26 # is there already terminated thread.
27 # * th.join(thread1,...)
28 # wait for specified thread(s).
29 # * th.join_nowait(threa1,...)
30 # specifies thread(s) to wait. non-blocking.
32 # waits until any of specified threads is terminated.
34 # waits until all of specified threads are terminated.
35 # if a block is supplied for the method, evaluates it for
36 # each thread termination.
43 RCS_ID='-$Id: thwait.rb,v 1.1.1.1 2002/02/01 06:36:19 tacyas Exp $-'
45 Exception2MessageMapper.extend_to(binding)
46 def_exception("ErrNoWaitingThread", "No threads for waiting.")
47 def_exception("ErrNoFinishedThread", "No finished threads.")
49 def ThreadsWait.all_waits(*threads)
50 tw = ThreadsWait.new(*threads)
60 def initialize(*threads)
62 @wait_queue = Queue.new
63 join_nowait(*threads) unless threads.empty?
67 # threads - list threads to be synchronized
74 # is there any thread to be synchronized.
79 # is there already terminated thread.
90 # adds thread(s) to join, waits for any of waiting threads to terminate.
96 # adds thread(s) to join, no wait.
97 def join_nowait(*threads)
99 @threads.concat threads
101 Thread.start(th) do |t|
108 # waits for any of waiting threads to terminate
109 # if there is no thread to wait, raises ErrNoWaitingThread.
110 # if `nonblock' is true, and there is no terminated thread,
111 # raises ErrNoFinishedThread.
112 def next_wait(nonblock = nil)
113 ThreadsWait.fail ErrNoWaitingThread if @threads.empty?
115 @threads.delete(th = @wait_queue.pop(nonblock))
118 ThreadsWait.fail ErrNoFinishedThread
122 # waits until all of specified threads are terminated.
123 # if a block is supplied for the method, evaluates it for
124 # each thread termination.
126 until @threads.empty?
128 yield th if block_given?