In Files

  • eval.c

Thread

Thread encapsulates the behavior of a thread of execution, including the main thread of the Ruby script.

In the descriptions of the methods in this class, the parameter sym refers to a symbol, which is either a quoted string or a Symbol (such as :name).

Public Class Methods

abort_on_exception => true or false click to toggle source

Returns the status of the global “abort on exception'' condition. The default is false. When set to true, or if the global $DEBUG flag is true (perhaps because the command line option -d was specified) all threads will abort (the process will exit(0)) if an exception is raised in any thread. See also Thread::abort_on_exception=.

 
               static VALUE
rb_thread_s_abort_exc()
{
    return ruby_thread_abort?Qtrue:Qfalse;
}
            
abort_on_exception= boolean => true or false click to toggle source

When set to true, all threads will abort if an exception is raised. Returns the new state.

Thread.abort_on_exception = true
t1 = Thread.new do
  puts  "In new thread"
  raise "Exception from thread"
end
sleep(1)
puts "not reached"

produces:

In new thread
prog.rb:4: Exception from thread (RuntimeError)
 from prog.rb:2:in `initialize'
 from prog.rb:2:in `new'
 from prog.rb:2
 
               static VALUE
rb_thread_s_abort_exc_set(self, val)
    VALUE self, val;
{
    rb_secure(4);
    ruby_thread_abort = RTEST(val);
    return val;
}
            
critical => true or false click to toggle source

Returns the status of the global “thread critical'' condition.

 
               static VALUE
rb_thread_critical_get()
{
    return rb_thread_critical?Qtrue:Qfalse;
}
            
critical= boolean => true or false click to toggle source

Sets the status of the global “thread critical'' condition and returns it. When set to true, prohibits scheduling of any existing thread. Does not block new threads from being created and run. Certain thread operations (such as stopping or killing a thread, sleeping in the current thread, and raising an exception) may cause a thread to be scheduled even when in a critical section. Thread::critical is not intended for daily use: it is primarily there to support folks writing threading libraries.

 
               static VALUE
rb_thread_critical_set(obj, val)
    VALUE obj, val;
{
    rb_thread_critical = RTEST(val);
    return val;
}
            
current => thread click to toggle source

Returns the currently executing thread.

Thread.current   #=> #<Thread:0x401bdf4c run>
 
               VALUE
rb_thread_current()
{
    return curr_thread->thread;
}
            
exit => thread click to toggle source

Terminates the currently running thread and schedules another thread to be run. If this thread is already marked to be killed, exit returns the Thread. If this is the main thread, or the last thread, exit the process.

 
               static VALUE
rb_thread_exit()
{
    return rb_thread_kill(curr_thread->thread);
}
            
fork([args]*) {|args| block } => thread click to toggle source

Basically the same as Thread::new. However, if class Thread is subclassed, then calling start in that subclass will not invoke the subclass's initialize method.

 
               static VALUE
rb_thread_start(klass, args)
    VALUE klass, args;
{
    if (!rb_block_given_p()) {
        rb_raise(rb_eThreadError, "must be called with a block");
    }
    return rb_thread_start_0(rb_thread_yield, args, rb_thread_alloc(klass));
}
            
kill(thread) => thread click to toggle source

Causes the given thread to exit (see Thread::exit).

count = 0
a = Thread.new { loop { count += 1 } }
sleep(0.1)       #=> 0
Thread.kill(a)   #=> #<Thread:0x401b3d30 dead>
count            #=> 93947
a.alive?         #=> false
 
               static VALUE
rb_thread_s_kill(obj, th)
    VALUE obj, th;
{
    return rb_thread_kill(th);
}
            
list => array click to toggle source

Returns an array of Thread objects for all threads that are either runnable or stopped.

Thread.new { sleep(200) }
Thread.new { 1000000.times {|i| i*i } }
Thread.new { Thread.stop }
Thread.list.each {|t| p t}

produces:

#<Thread:0x401b3e84 sleep>
#<Thread:0x401b3f38 run>
#<Thread:0x401b3fb0 sleep>
#<Thread:0x401bdf4c run>
 
               VALUE
rb_thread_list()
{
    rb_thread_t th;
    VALUE ary = rb_ary_new();

    FOREACH_THREAD(th) {
        switch (th->status) {
          case THREAD_RUNNABLE:
          case THREAD_STOPPED:
          case THREAD_TO_KILL:
            rb_ary_push(ary, th->thread);
          default:
            break;
        }
    }
    END_FOREACH(th);

    return ary;
}
            
main => thread click to toggle source

Returns the main thread for the process.

Thread.main   #=> #<Thread:0x401bdf4c run>
 
               VALUE
rb_thread_main()
{
    return main_thread->thread;
}
            
new([arg]*) {|args| block } => thread click to toggle source

Creates and runs a new thread to execute the instructions given in block. Any arguments passed to Thread::new are passed into the block.

x = Thread.new { sleep 0.1; print "x"; print "y"; print "z" }
a = Thread.new { print "a"; print "b"; sleep 0.2; print "c" }
x.join # Let the threads finish before
a.join # main thread exits...

produces:

abxyzc
 
               static VALUE
rb_thread_s_new(argc, argv, klass)
    int argc;
    VALUE *argv;
    VALUE klass;
{
    rb_thread_t th = rb_thread_alloc(klass);
    volatile VALUE *pos;

    pos = th->stk_pos;
    rb_obj_call_init(th->thread, argc, argv);
    if (th->stk_pos == 0) {
        rb_raise(rb_eThreadError, "uninitialized thread - check `%s#initialize'",
                 rb_class2name(klass));
    }

    return th->thread;
}
            
pass => nil click to toggle source

Invokes the thread scheduler to pass execution to another thread.

a = Thread.new { print "a"; Thread.pass;
                 print "b"; Thread.pass;
                 print "c" }
b = Thread.new { print "x"; Thread.pass;
                 print "y"; Thread.pass;
                 print "z" }
a.join
b.join

produces:

axbycz
 
               static VALUE
rb_thread_pass()
{
    rb_thread_schedule();
    return Qnil;
}
            
start([args]*) {|args| block } => thread click to toggle source

Basically the same as Thread::new. However, if class Thread is subclassed, then calling start in that subclass will not invoke the subclass's initialize method.

 
               static VALUE
rb_thread_start(klass, args)
    VALUE klass, args;
{
    if (!rb_block_given_p()) {
        rb_raise(rb_eThreadError, "must be called with a block");
    }
    return rb_thread_start_0(rb_thread_yield, args, rb_thread_alloc(klass));
}
            
stop => nil click to toggle source

Stops execution of the current thread, putting it into a “sleep'' state, and schedules execution of another thread. Resets the “critical'' condition to false.

a = Thread.new { print "a"; Thread.stop; print "c" }
Thread.pass
print "b"
a.run
a.join

produces:

abc
 
               VALUE
rb_thread_stop()
{
    enum rb_thread_status last_status = THREAD_RUNNABLE;

    rb_thread_critical = 0;
    if (curr_thread == curr_thread->next) {
        rb_raise(rb_eThreadError, "stopping only thread\n\tnote: use sleep to stop forever");
    }
    if (curr_thread->status == THREAD_TO_KILL)
        last_status = THREAD_TO_KILL;
    curr_thread->status = THREAD_STOPPED;
    rb_thread_schedule();
    curr_thread->status = last_status;

    return Qnil;
}
            

Public Instance Methods

thr[sym] => obj or nil click to toggle source

Attribute Reference—Returns the value of a thread-local variable, using either a symbol or a string name. If the specified variable does not exist, returns nil.

a = Thread.new { Thread.current["name"] = "A"; Thread.stop }
b = Thread.new { Thread.current[:name]  = "B"; Thread.stop }
c = Thread.new { Thread.current["name"] = "C"; Thread.stop }
Thread.list.each {|x| puts "#{x.inspect}: #{x[:name]}" }

produces:

#<Thread:0x401b3b3c sleep>: C
#<Thread:0x401b3bc8 sleep>: B
#<Thread:0x401b3c68 sleep>: A
#<Thread:0x401bdf4c run>:
 
               static VALUE
rb_thread_aref(thread, id)
    VALUE thread, id;
{
    return rb_thread_local_aref(thread, rb_to_id(id));
}
            
thr[sym] = obj => obj click to toggle source

Attribute Assignment—Sets or creates the value of a thread-local variable, using either a symbol or a string. See also Thread#[].

 
               static VALUE
rb_thread_aset(thread, id, val)
    VALUE thread, id, val;
{
    return rb_thread_local_aset(thread, rb_to_id(id), val);
}
            
abort_on_exception => true or false click to toggle source

Returns the status of the thread-local “abort on exception'' condition for thr. The default is false. See also Thread::abort_on_exception=.

 
               static VALUE
rb_thread_abort_exc(thread)
    VALUE thread;
{
    return rb_thread_check(thread)->abort?Qtrue:Qfalse;
}
            
abort_on_exception= boolean => true or false click to toggle source

When set to true, causes all threads (including the main program) to abort if an exception is raised in thr. The process will effectively exit(0).

 
               static VALUE
rb_thread_abort_exc_set(thread, val)
    VALUE thread, val;
{
    rb_secure(4);
    rb_thread_check(thread)->abort = RTEST(val);
    return val;
}
            
alive? => true or false click to toggle source

Returns true if thr is running or sleeping.

thr = Thread.new { }
thr.join                #=> #<Thread:0x401b3fb0 dead>
Thread.current.alive?   #=> true
thr.alive?              #=> false
 
               VALUE
rb_thread_alive_p(thread)
    VALUE thread;
{
    rb_thread_t th = rb_thread_check(thread);

    if (rb_thread_dead(th)) return Qfalse;
    return Qtrue;
}
            
exit => thr click to toggle source
kill => thr
terminate => thr

Terminates thr and schedules another thread to be run, returning the terminated Thread. If this is the main thread, or the last thread, exits the process.

 
               VALUE
rb_thread_kill(thread)
    VALUE thread;
{
    rb_thread_t th = rb_thread_check(thread);

    rb_kill_thread(th, 0);
    return thread;
}
            
exit! => thr click to toggle source

Terminates thr without calling ensure clauses and schedules another thread to be run, returning the terminated Thread. If this is the main thread, or the last thread, exits the process.

See Thread#exit for the safer version.

 
               static VALUE
rb_thread_kill_bang(thread)
    VALUE thread;
{
    rb_thread_t th = rb_thread_check(thread);
    rb_kill_thread(th, THREAD_NO_ENSURE);
    return thread;
}
            
group => thgrp or nil click to toggle source

Returns the ThreadGroup which contains thr, or nil if the thread is not a member of any group.

Thread.main.group   #=> #<ThreadGroup:0x4029d914>
 
               VALUE
rb_thread_group(thread)
    VALUE thread;
{
    VALUE group = rb_thread_check(thread)->thgroup;
    if (!group) {
        group = Qnil;
    }
    return group;
}
            
inspect => string click to toggle source

Dump the name, id, and status of thr to a string.

 
               static VALUE
rb_thread_inspect(thread)
    VALUE thread;
{
    char *cname = rb_obj_classname(thread);
    rb_thread_t th = rb_thread_check(thread);
    const char *status = thread_status_name(th->status);
    VALUE str;
    size_t len = strlen(cname)+7+16+9+1;

    str = rb_str_new(0, len); /* 7:tags 16:addr 9:status 1:nul */
    snprintf(RSTRING(str)->ptr, len, "#<%s:0x%lx %s>", cname, thread, status);
    RSTRING(str)->len = strlen(RSTRING(str)->ptr);
    OBJ_INFECT(str, thread);

    return str;
}
            
join => thr click to toggle source
join(limit) => thr

The calling thread will suspend execution and run thr. Does not return until thr exits or until 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 and $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 x thread finish, a will be killed on exit.

produces:

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)

produces:

tick...
Waiting
tick...
Waitingtick...

tick...
 
               static VALUE
rb_thread_join_m(argc, argv, thread)
    int argc;
    VALUE *argv;
    VALUE thread;
{
    VALUE limit;
    double delay = DELAY_INFTY;

    rb_scan_args(argc, argv, "01", &limit);
    if (!NIL_P(limit)) delay = rb_num2dbl(limit);
    if (!rb_thread_join0(rb_thread_check(thread), delay))
        return Qnil;
    return thread;
}
            
key?(sym) => true or false click to toggle source

Returns true if the given string (or symbol) exists as a thread-local variable.

me = Thread.current
me[:oliver] = "a"
me.key?(:oliver)    #=> true
me.key?(:stanley)   #=> false
 
               static VALUE
rb_thread_key_p(thread, id)
    VALUE thread, id;
{
    rb_thread_t th = rb_thread_check(thread);

    if (!th->locals) return Qfalse;
    if (st_lookup(th->locals, rb_to_id(id), 0))
        return Qtrue;
    return Qfalse;
}
            
keys => array click to toggle source

Returns an an array of the names of the thread-local variables (as Symbols).

thr = Thread.new do
  Thread.current[:cat] = 'meow'
  Thread.current["dog"] = 'woof'
end
thr.join   #=> #<Thread:0x401b3f10 dead>
thr.keys   #=> [:dog, :cat]
 
               static VALUE
rb_thread_keys(thread)
    VALUE thread;
{
    rb_thread_t th = rb_thread_check(thread);
    VALUE ary = rb_ary_new();

    if (th->locals) {
        st_foreach(th->locals, thread_keys_i, ary);
    }
    return ary;
}
            
exit => thr click to toggle source
kill => thr
terminate => thr

Terminates thr and schedules another thread to be run, returning the terminated Thread. If this is the main thread, or the last thread, exits the process.

 
               VALUE
rb_thread_kill(thread)
    VALUE thread;
{
    rb_thread_t th = rb_thread_check(thread);

    rb_kill_thread(th, 0);
    return thread;
}
            
kill! => thr click to toggle source

Terminates thr without calling ensure clauses and schedules another thread to be run, returning the terminated Thread. If this is the main thread, or the last thread, exits the process.

See Thread#exit for the safer version.

 
               static VALUE
rb_thread_kill_bang(thread)
    VALUE thread;
{
    rb_thread_t th = rb_thread_check(thread);
    rb_kill_thread(th, THREAD_NO_ENSURE);
    return thread;
}
            
priority => integer click to toggle source

Returns the priority of thr. Default is inherited from the current thread which creating the new thread, or zero for the initial main thread; higher-priority threads will run before lower-priority threads.

Thread.current.priority   #=> 0
 
               static VALUE
rb_thread_priority(thread)
    VALUE thread;
{
    return INT2NUM(rb_thread_check(thread)->priority);
}
            
priority= integer => thr click to toggle source

Sets the priority of thr to integer. Higher-priority threads will run before lower-priority threads.

count1 = count2 = 0
a = Thread.new do
      loop { count1 += 1 }
    end
a.priority = -1

b = Thread.new do
      loop { count2 += 1 }
    end
b.priority = -2
sleep 1   #=> 1
Thread.critical = 1
count1    #=> 622504
count2    #=> 5832
 
               static VALUE
rb_thread_priority_set(thread, prio)
    VALUE thread, prio;
{
    rb_thread_t th;

    rb_secure(4);
    th = rb_thread_check(thread);

    th->priority = NUM2INT(prio);
    rb_thread_schedule();
    return prio;
}
            
raise(exception) click to toggle source

Raises an exception (see Kernel::raise) from thr. The caller does not have to be thr.

Thread.abort_on_exception = true
a = Thread.new { sleep(200) }
a.raise("Gotcha")

produces:

prog.rb:3: Gotcha (RuntimeError)
 from prog.rb:2:in `initialize'
 from prog.rb:2:in `new'
 from prog.rb:2
 
               static VALUE
rb_thread_raise_m(argc, argv, thread)
    int argc;
    VALUE *argv;
    VALUE thread;
{
    rb_thread_t th = rb_thread_check(thread);

    if (ruby_safe_level > th->safe) {
        rb_secure(4);
    }
    rb_thread_raise(argc, argv, th);
    return Qnil;                /* not reached */
}
            
run => thr click to toggle source

Wakes up thr, making it eligible for scheduling. If not in a critical section, then invokes the scheduler.

a = Thread.new { puts "a"; Thread.stop; puts "c" }
Thread.pass
puts "Got here"
a.run
a.join

produces:

a
Got here
c
 
               VALUE
rb_thread_run(thread)
    VALUE thread;
{
    rb_thread_wakeup(thread);
    if (!rb_thread_critical) rb_thread_schedule();

    return thread;
}
            
safe_level => integer click to toggle source

Returns the safe level in effect for thr. Setting thread-local safe levels can help when implementing sandboxes which run insecure code.

thr = Thread.new { $SAFE = 3; sleep }
Thread.current.safe_level   #=> 0
thr.safe_level              #=> 3
 
               static VALUE
rb_thread_safe_level(thread)
    VALUE thread;
{
    rb_thread_t th;

    th = rb_thread_check(thread);
    if (th == curr_thread) {
        return INT2NUM(ruby_safe_level);
    }
    return INT2NUM(th->safe);
}
            
status => string, false or nil click to toggle source

Returns the status of thr: “sleep'' if thr is sleeping or waiting on I/O, “run'' if thr is executing, “aborting'' if thr is aborting, false if thr terminated normally, and nil if thr terminated with an exception.

a = Thread.new { raise("die now") }
b = Thread.new { Thread.stop }
c = Thread.new { Thread.exit }
d = Thread.new { sleep }
Thread.critical = true
d.kill                  #=> #<Thread:0x401b3678 aborting>
a.status                #=> nil
b.status                #=> "sleep"
c.status                #=> false
d.status                #=> "aborting"
Thread.current.status   #=> "run"
 
               static VALUE
rb_thread_status_name(thread)
    VALUE thread;
{
    rb_thread_t th = rb_thread_check(thread);

    if (rb_thread_dead(th)) {
        if (!NIL_P(th->errinfo) && (th->flags & RAISED_EXCEPTION))
            return Qnil;
        return Qfalse;
    }

    return rb_str_new2(thread_status_name(th->status));
}
            
stop? => true or false click to toggle source

Returns true if thr is dead or sleeping.

a = Thread.new { Thread.stop }
b = Thread.current
a.stop?   #=> true
b.stop?   #=> false
 
               static VALUE
rb_thread_stop_p(thread)
    VALUE thread;
{
    rb_thread_t th = rb_thread_check(thread);

    if (rb_thread_dead(th)) return Qtrue;
    if (th->status == THREAD_STOPPED) return Qtrue;
    return Qfalse;
}
            
terminate => thr click to toggle source

Terminates thr and schedules another thread to be run, returning the terminated Thread. If this is the main thread, or the last thread, exits the process.

 
               VALUE
rb_thread_kill(thread)
    VALUE thread;
{
    rb_thread_t th = rb_thread_check(thread);

    rb_kill_thread(th, 0);
    return thread;
}
            
terminate! => thr click to toggle source

Terminates thr without calling ensure clauses and schedules another thread to be run, returning the terminated Thread. If this is the main thread, or the last thread, exits the process.

See Thread#exit for the safer version.

 
               static VALUE
rb_thread_kill_bang(thread)
    VALUE thread;
{
    rb_thread_t th = rb_thread_check(thread);
    rb_kill_thread(th, THREAD_NO_ENSURE);
    return thread;
}
            
value => obj click to toggle source

Waits for thr to complete (via Thread#join) and returns its value.

a = Thread.new { 2 + 2 }
a.value   #=> 4
 
               static VALUE
rb_thread_value(thread)
    VALUE thread;
{
    rb_thread_t th = rb_thread_check(thread);

    while (!rb_thread_join0(th, DELAY_INFTY));

    return th->result;
}
            
wakeup => thr click to toggle source

Marks thr as eligible for scheduling (it may still remain blocked on I/O, however). Does not invoke the scheduler (see Thread#run).

c = Thread.new { Thread.stop; puts "hey!" }
c.wakeup

produces:

hey!
 
               VALUE
rb_thread_wakeup(thread)
    VALUE thread;
{
    if (!RTEST(rb_thread_wakeup_alive(thread)))
        rb_raise(rb_eThreadError, "killed thread");
    return thread;
}