Class: Thread
Overview
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
).
Class Method Summary collapse
-
.abort_on_exception ⇒ Boolean
Returns the status of the global “abort on exception” condition.
-
.abort_on_exception=(boolean) ⇒ Boolean
When set to
true
, all threads will abort if an exception is raised. -
.critical ⇒ Boolean
Returns the status of the global “thread critical” condition.
-
.critical=(boolean) ⇒ Boolean
Sets the status of the global “thread critical” condition and returns it.
-
.current ⇒ Object
Returns the currently executing thread.
-
.exit ⇒ Object
Terminates the currently running thread and schedules another thread to be run.
-
.fork ⇒ Object
Basically the same as
Thread::new
. -
.kill(thread) ⇒ Object
Causes the given thread to exit (see
Thread::exit
). -
.list ⇒ Array
Returns an array of
Thread
objects for all threads that are either runnable or stopped. -
.main ⇒ Object
Returns the main thread for the process.
-
.new([arg]) {|args| ... } ⇒ Object
Creates and runs a new thread to execute the instructions given in block.
-
.pass ⇒ nil
Invokes the thread scheduler to pass execution to another thread.
-
.start ⇒ Object
Basically the same as
Thread::new
. -
.stop ⇒ nil
Stops execution of the current thread, putting it into a “sleep” state, and schedules execution of another thread.
Instance Method Summary collapse
-
#[](sym) ⇒ Object?
Attribute Reference—Returns the value of a thread-local variable, using either a symbol or a string name.
-
#[]=(sym) ⇒ Object
Attribute Assignment—Sets or creates the value of a thread-local variable, using either a symbol or a string.
-
#abort_on_exception ⇒ Boolean
Returns the status of the thread-local “abort on exception” condition for thr.
-
#abort_on_exception=(boolean) ⇒ Boolean
When set to
true
, causes all threads (including the main program) to abort if an exception is raised in thr. -
#alive? ⇒ Boolean
Returns
true
if thr is running or sleeping. -
#exit ⇒ Object
Terminates thr and schedules another thread to be run, returning the terminated
Thread
. -
#exit! ⇒ Object
Terminates thr without calling ensure clauses and schedules another thread to be run, returning the terminated
Thread
. -
#group ⇒ nil
Returns the
ThreadGroup
which contains thr, or nil if the thread is not a member of any group. -
#new([arg]) {|args| ... } ⇒ Object
constructor
Creates and runs a new thread to execute the instructions given in block.
-
#inspect ⇒ String
Dump the name, id, and status of thr to a string.
-
#join ⇒ Object
The calling thread will suspend execution and run thr.
-
#key?(sym) ⇒ Boolean
Returns
true
if the given string (or symbol) exists as a thread-local variable. -
#keys ⇒ Array
Returns an an array of the names of the thread-local variables (as Symbols).
-
#kill ⇒ Object
Terminates thr and schedules another thread to be run, returning the terminated
Thread
. -
#kill! ⇒ Object
Terminates thr without calling ensure clauses and schedules another thread to be run, returning the terminated
Thread
. -
#priority ⇒ Integer
Returns the priority of thr.
-
#priority=(integer) ⇒ Object
Sets the priority of thr to integer.
-
#raise(exception) ⇒ Object
Raises an exception (see
Kernel::raise
) from thr. -
#run ⇒ Object
Wakes up thr, making it eligible for scheduling.
-
#safe_level ⇒ Integer
Returns the safe level in effect for thr.
-
#status ⇒ String, ...
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, andnil
if thr terminated with an exception. -
#stop? ⇒ Boolean
Returns
true
if thr is dead or sleeping. -
#terminate ⇒ Object
Terminates thr and schedules another thread to be run, returning the terminated
Thread
. -
#terminate! ⇒ Object
Terminates thr without calling ensure clauses and schedules another thread to be run, returning the terminated
Thread
. -
#value ⇒ Object
Waits for thr to complete (via
Thread#join
) and returns its value. -
#wakeup ⇒ Object
Marks thr as eligible for scheduling (it may still remain blocked on I/O, however).
Constructor Details
#new([arg]) {|args| ... } ⇒ Object
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
12019 12020 12021 |
# File 'eval.c', line 12019 static VALUE rb_thread_initialize(thread, args) VALUE thread, args; |
Class Method Details
.abort_on_exception ⇒ Boolean
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=
.
11556 11557 11558 11559 11560 |
# File 'eval.c', line 11556
static VALUE
rb_thread_s_abort_exc()
{
return ruby_thread_abort?Qtrue:Qfalse;
}
|
.abort_on_exception=(boolean) ⇒ Boolean
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
11587 11588 11589 |
# File 'eval.c', line 11587 static VALUE rb_thread_s_abort_exc_set(self, val) VALUE self, val; |
.critical ⇒ Boolean
Returns the status of the global “thread critical” condition.
12225 12226 12227 12228 12229 |
# File 'eval.c', line 12225
static VALUE
rb_thread_critical_get()
{
return rb_thread_critical?Qtrue:Qfalse;
}
|
.critical=(boolean) ⇒ Boolean
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.
12246 12247 12248 |
# File 'eval.c', line 12246 static VALUE rb_thread_critical_set(obj, val) VALUE obj, val; |
.current ⇒ Object
Returns the currently executing thread.
Thread.current #=> #<Thread:0x401bdf4c run>
11120 11121 11122 11123 11124 |
# File 'eval.c', line 11120
VALUE
rb_thread_current()
{
return curr_thread->thread;
}
|
.exit ⇒ Object
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.
11340 11341 11342 11343 11344 |
# File 'eval.c', line 11340
static VALUE
rb_thread_exit()
{
return rb_thread_kill(curr_thread->thread);
}
|
.start([args]) {|args| ... } ⇒ Object .fork([args]) {|args| ... } ⇒ Object
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.
12051 12052 12053 |
# File 'eval.c', line 12051 static VALUE rb_thread_start(klass, args) VALUE klass, args; |
.kill(thread) ⇒ Object
11322 11323 11324 |
# File 'eval.c', line 11322 static VALUE rb_thread_s_kill(obj, th) VALUE obj, th; |
.list ⇒ Array
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>
11163 11164 11165 11166 11167 11168 11169 11170 11171 11172 11173 11174 11175 11176 11177 11178 11179 11180 11181 11182 |
# File 'eval.c', line 11163
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 ⇒ Object
Returns the main thread for the process.
Thread.main #=> #<Thread:0x401bdf4c run>
11136 11137 11138 11139 11140 |
# File 'eval.c', line 11136
VALUE
rb_thread_main()
{
return main_thread->thread;
}
|
.new([arg]) {|args| ... } ⇒ Object
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
11981 11982 11983 |
# File 'eval.c', line 11981 static VALUE rb_thread_s_new(argc, argv, klass) int argc; |
.pass ⇒ nil
11367 11368 11369 11370 11371 11372 |
# File 'eval.c', line 11367
static VALUE
rb_thread_pass()
{
rb_thread_schedule();
return Qnil;
}
|
.start([args]) {|args| ... } ⇒ Object .fork([args]) {|args| ... } ⇒ Object
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.
12051 12052 12053 |
# File 'eval.c', line 12051 static VALUE rb_thread_start(klass, args) VALUE klass, args; |
.stop ⇒ nil
11394 11395 11396 11397 11398 11399 11400 11401 11402 11403 11404 11405 11406 11407 11408 11409 11410 |
# File 'eval.c', line 11394
VALUE
rb_thread_stop()
{
enum 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;
}
|
Instance Method Details
#[](sym) ⇒ Object?
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>:
12447 12448 12449 |
# File 'eval.c', line 12447 static VALUE rb_thread_aref(thread, id) VALUE thread, id; |
#[]=(sym) ⇒ Object
Attribute Assignment—Sets or creates the value of a thread-local variable, using either a symbol or a string. See also Thread#[]
.
12488 12489 12490 |
# File 'eval.c', line 12488 static VALUE rb_thread_aset(thread, id, val) VALUE thread, id, val; |
#abort_on_exception ⇒ Boolean
Returns the status of the thread-local “abort on exception” condition for thr. The default is false
. See also Thread::abort_on_exception=
.
11606 11607 11608 |
# File 'eval.c', line 11606 static VALUE rb_thread_abort_exc(thread) VALUE thread; |
#abort_on_exception=(boolean) ⇒ Boolean
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)
.
11623 11624 11625 |
# File 'eval.c', line 11623 static VALUE rb_thread_abort_exc_set(thread, val) VALUE thread, val; |
#alive? ⇒ Boolean
12136 12137 12138 |
# File 'eval.c', line 12136 static VALUE rb_thread_alive_p(thread) VALUE thread; |
#exit ⇒ Object #kill ⇒ Object #terminate ⇒ Object
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.
11275 11276 11277 |
# File 'eval.c', line 11275 VALUE rb_thread_kill(thread) VALUE thread; |
#exit! ⇒ Object #kill! ⇒ Object #terminate! ⇒ Object
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.
11299 11300 11301 |
# File 'eval.c', line 11299 static VALUE rb_thread_kill_bang(thread) VALUE thread; |
#group ⇒ nil
11643 11644 11645 |
# File 'eval.c', line 11643 VALUE rb_thread_group(thread) VALUE thread; |
#inspect ⇒ String
Dump the name, id, and status of thr to a string.
12565 12566 12567 |
# File 'eval.c', line 12565 static VALUE rb_thread_inspect(thread) VALUE thread; |
#join ⇒ Object #join(limit) ⇒ Object
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...
11093 11094 11095 |
# File 'eval.c', line 11093 static VALUE rb_thread_join_m(argc, argv, thread) int argc; |
#key?(sym) ⇒ Boolean
12509 12510 12511 |
# File 'eval.c', line 12509 static VALUE rb_thread_key_p(thread, id) VALUE thread, id; |
#keys ⇒ Array
12545 12546 12547 |
# File 'eval.c', line 12545 static VALUE rb_thread_keys(thread) VALUE thread; |
#exit ⇒ Object #kill ⇒ Object #terminate ⇒ Object
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.
11275 11276 11277 |
# File 'eval.c', line 11275 VALUE rb_thread_kill(thread) VALUE thread; |
#exit! ⇒ Object #kill! ⇒ Object #terminate! ⇒ Object
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.
11299 11300 11301 |
# File 'eval.c', line 11299 static VALUE rb_thread_kill_bang(thread) VALUE thread; |
#priority ⇒ Integer
11469 11470 11471 |
# File 'eval.c', line 11469 static VALUE rb_thread_priority(thread) VALUE thread; |
#priority=(integer) ⇒ Object
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
11500 11501 11502 |
# File 'eval.c', line 11500 static VALUE rb_thread_priority_set(thread, prio) VALUE thread, prio; |
#raise(exception) ⇒ Object
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
12391 12392 12393 |
# File 'eval.c', line 12391 static VALUE rb_thread_raise_m(argc, argv, thread) int argc; |
#run ⇒ Object
11234 11235 11236 |
# File 'eval.c', line 11234 VALUE rb_thread_run(thread) VALUE thread; |
#safe_level ⇒ Integer
11527 11528 11529 |
# File 'eval.c', line 11527 static VALUE rb_thread_safe_level(thread) VALUE thread; |
#status ⇒ String, ...
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"
12108 12109 12110 |
# File 'eval.c', line 12108 static VALUE rb_thread_status(thread) VALUE thread; |
#stop? ⇒ Boolean
12159 12160 12161 |
# File 'eval.c', line 12159 static VALUE rb_thread_stop_p(thread) VALUE thread; |
#exit ⇒ Object #kill ⇒ Object #terminate ⇒ Object
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.
11275 11276 11277 |
# File 'eval.c', line 11275 VALUE rb_thread_kill(thread) VALUE thread; |
#exit! ⇒ Object #kill! ⇒ Object #terminate! ⇒ Object
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.
11299 11300 11301 |
# File 'eval.c', line 11299 static VALUE rb_thread_kill_bang(thread) VALUE thread; |
#value ⇒ Object
12073 12074 12075 |
# File 'eval.c', line 12073 static VALUE rb_thread_value(thread) VALUE thread; |
#wakeup ⇒ Object
11200 11201 11202 |
# File 'eval.c', line 11200 VALUE rb_thread_wakeup(thread) VALUE thread; |