This class watches for termination of multiple threads. Basic functionality (wait until specified threads have terminated) can be accessed through the class method ::all_waits. Finer control can be gained using instance methods.
Example:
ThreadsWait.all_wait(thr1, thr2, ...) do |t| STDERR.puts "Thread #{t} has terminated." end
Waits until all specified threads have terminated. If a block is provided, it is executed for each thread termination.
# File thwait.rb, line 64
def ThreadsWait.all_waits(*threads) # :yield: thread
tw = ThreadsWait.new(*threads)
if block_given?
tw.all_waits do |th|
yield th
end
else
tw.all_waits
end
end
Creates a ThreadsWait object, specifying the threads to wait on. Non-blocking.
# File thwait.rb, line 79
def initialize(*threads)
@threads = []
@wait_queue = Queue.new
join_nowait(*threads) unless threads.empty?
end
Waits until all of the specified threads are terminated. If a block is supplied for the method, it is executed for each thread termination.
Raises exceptions in the same manner as next_wait.
# File thwait.rb, line 151
def all_waits
until @threads.empty?
th = next_wait
yield th if block_given?
end
end
Returns true if there are no threads to be synchronized.
# File thwait.rb, line 91
def empty?
@threads.empty?
end
Returns true if any thread has terminated.
# File thwait.rb, line 98
def finished?
!@wait_queue.empty?
end
Waits for specified threads to terminate.
# File thwait.rb, line 105
def join(*threads)
join_nowait(*threads)
next_wait
end
Specifies the threads that this object will wait for, but does not actually wait.
# File thwait.rb, line 114
def join_nowait(*threads)
threads.flatten!
@threads.concat threads
for th in threads
Thread.start(th) do |t|
begin
t.join
ensure
@wait_queue.push t
end
end
end
end
Waits until any of the specified threads has terminated, and returns the one that does.
If there is no thread to wait, raises ErrNoWaitingThread. If
nonblock is true, and there is no terminated thread, raises
ErrNoFinishedThread.
# File thwait.rb, line 135
def next_wait(nonblock = nil)
ThreadsWait.fail ErrNoWaitingThread if @threads.empty?
begin
@threads.delete(th = @wait_queue.pop(nonblock))
th
rescue ThreadError
ThreadsWait.fail ErrNoFinishedThread
end
end
Commenting is here to help enhance the documentation. For example, code samples, or clarification of the documentation.
If you have questions about Ruby or the documentation, please post to one of the Ruby mailing lists. You will get better, faster, help that way.
If you wish to post a correction of the docs, please do so, but also file bug report so that it can be corrected for the next release. Thank you.
If you want to help improve the Ruby documentation, please visit Documenting-ruby.org.