Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →
Thread#join
static VALUE
thread_join_m(int argc, VALUE *argv, VALUE self)
{
VALUE timeout = Qnil;
rb_hrtime_t rel = 0, *limit = 0;
if (rb_check_arity(argc, 0, 1)) {
timeout = argv[0];
}
// Convert the timeout eagerly, so it's always converted and deterministic
/*
* This supports INFINITY and negative values, so we can't use
* rb_time_interval right now...
*/
if (NIL_P(timeout)) {
/* unlimited */
}
else if (FIXNUM_P(timeout)) {
rel = rb_sec2hrtime(NUM2TIMET(timeout));
limit = &rel;
}
else {
limit = double2hrtime(&rel, rb_num2dbl(timeout));
}
return thread_join(rb_thread_ptr(self), timeout, limit);
}
The calling thread will suspend execution and run this thr.
Does not return until thr exits or until the given limit seconds have passed.
If the time limit expires, nil will be returned, otherwise thr is returned.
Any threads not joined will be killed when the main program exits.
If thr had previously raised an exception and the ::abort_on_exception or $DEBUG flags are not set, (so the exception has not yet been processed), it will be processed at this time.
a = Thread.new { print "a"; sleep(10); print "b"; print "c" } x = Thread.new { print "x"; Thread.pass; print "y"; print "z" } x.join # Let thread x finish, thread a will be killed on exit. #=> "axyz"
The following example illustrates the limit parameter.
y = Thread.new { 4.times { sleep 0.1; puts 'tick... ' }} puts "Waiting" until y.join(0.15)
This will produce:
tick... Waiting tick... Waiting tick... tick...
Ruby version changes
-
3.0
-
Thread#joininvokes the scheduler hooksblock/unblockin a non-blocking execution context. [Feature #16786]
-