Programming Ruby

The Pragmatic Programmer's Guide

Previous < Contents ^
Next >
class Thread
Parent: Object
Version: 1.6


abort_on_exception abort_on_exception= critical critical= current exit fork kill list main new pass start stop [ ] [ ]= abort_on_exception abort_on_exception= alive? exit join key? kill priority priority= raise run safe_level status stop? value wakeup

Thread encapsulates the behavior of a thread of execution, including the main thread of the Ruby script. See the tutorial in Chapter 11, beginning on page 111.

In the descriptions that follow, the parameter aSymbol refers to a symbol, which is either a quoted string or a Symbol (such as :name).
class methods
abort_on_exception Thread.abort_on_exception -> true or false
Returns the status of the global ``abort on exception'' condition. The default is false. When set to true, will cause all threads to abort (the process will exit(0)) if an exception is raised in any thread. See also Thread.abort_on_exception= .

abort_on_exception= Thread.abort_on_exception= aBoolean-> true or false

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

Thread.abort_on_exception = true
t1 = do
  puts  "In second thread"
  raise "Raise exception"
print "not reached\n"
In second thread
prog.rb:4: Raise exception (RuntimeError)
	from prog.rb:2:in `initialize'
	from prog.rb:2:in `new'
	from prog.rb:2

critical Thread.critical -> true or false

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

critical= Thread.critical= aBoolean -> true or false

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.

count=0 { while true; sleep(1); print "a "; count+=1; end }
while count < 3 do end # no-op wait
Thread.critical = true
puts "no more a's will come out."
a a a no more a's will come out.

current Thread.current -> aThread

Returns the currently executing thread.

Thread.current #<Thread:0x401be5c8 run>

exit Thread.exit

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.

fork Thread.fork { block } -> aThread

Synonym for .

kill Thread.kill( aThread )

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

count = 0
a = { while true do  count += 1 end }
sleep(1) 1
Thread.kill(a) #<Thread:0x401b5cac dead>
count 903877
a.alive? false

list Thread.list -> anArray

Returns an array of Thread objects for all threads that are either runnable or stopped. { sleep(200) } { 1000000.times {|i| i*i } } { Thread.stop }
l = Thread.list
l [#<Thread:0x401b5644 sleep>, #<Thread:0x401b59f0 run>, #<Thread:0x401b5cac sleep>, #<Thread:0x401be5c8 run>]

main Thread.main -> aThread

Returns the main thread for the process.

Thread.main #<Thread:0x401be5c8 run>

new [ arg ]* ) {| args | block }

-> aThread

Creates a new thread to execute the instructions given in block, and begins running it. Any arguments passed to are passed into the block.

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

pass Thread.pass

Invokes the thread scheduler to pass execution to another thread.

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

start Thread.start( [ args ]* ) {| args | block }

-> aThread

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

stop Thread.stop

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 = { print "a"; Thread.stop; print "c" }
print "b"

instance methods
[ ]

thr[ aSymbol ] -> anObject or nil

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.current["name"] = "A"; Thread.stop }
b = { Thread.current[:name]  = "B"; Thread.stop }
c = { Thread.current["name"] = "C"; Thread.stop }
Thread.list.each {|x| print x.inspect, x[:name], "\n" }
#<Thread:0x401b53c4 sleep>C
#<Thread:0x401b5734 sleep>B
#<Thread:0x401b5cac sleep>A
#<Thread:0x401be5c8 run>nil

[ ]=

thr[ aSymbol ] = anObject-> anObject

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

abort_on_exception thr.abort_on_exception -> true or false
Returns the status of the ``abort on exception'' condition for thr. The default is false. See also Thread.abort_on_exception= .

abort_on_exception= thr.abort_on_exception= true or false-> true or false

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).

alive? thr.alive? -> true or false

Returns true if thr is running or sleeping.

Thread.current.alive? true

exit thr.exit -> thr or nil

Terminates thr 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, exits the process.

join thr.join -> thr

The calling thread will suspend execution and run thr. Does not return until thr exits. Any threads not joined will be killed when the main program exits.

a = { print "a"; sleep(10); print "b"; print "c" }
x = { print "x"; Thread.pass; print "y"; print "z" }
x.join # Let x thread finish, a will be killed on exit.

key? thr.key?( aSymbol ) -> true or false

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

kill thr.kill

Synonym for Thread#exit .

priority thr.priority -> anInteger

Returns the priority of thr. Default is zero; higher-priority threads will run before lower-priority threads.

Thread.current.priority 0

priority= thr.priority= anInteger -> thr

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

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

b = do
      loop { count2 += 1 }
b.priority = -2
sleep 1 1
Thread.critical = 1
count1 577581
count2 5751

raise thr.raise( anException )

Raises an exception (see Kernel::raise on page 420 for details) from thr. The caller does not have to be thr.

Thread.abort_on_exception = true
a = { sleep(200) }
prog.rb:3: Gotcha (RuntimeError)
	from prog.rb:2:in `initialize'
	from prog.rb:2:in `new'
	from prog.rb:2

run -> thr

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

a = { puts "a"; Thread.stop; puts "c" }
puts "Got here"
Got here

safe_level thr.safe_level -> anInteger

Returns the safe level in effect for thr.

Thread.current.safe_level 0

status thr.status -> aString, false or nil

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

a = { raise("die now") }
b = { Thread.stop }
c = { Thread.exit }
a.status nil
b.status "sleep"
c.status false
Thread.current.status "run"

stop? thr.stop? -> true or false

Returns true if thr is dead or sleeping.

a = { Thread.stop }
b = Thread.current
a.stop? true
b.stop? false

value thr.value -> anObject

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

a = { 2+2 }
a.value 4

wakeup thr.wakeup -> thr

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.stop; puts "hey!" }

Previous < Contents ^
Next >

Extracted from the book "Programming Ruby - The Pragmatic Programmer's Guide"
Copyright © 2001 by Addison Wesley Longman, Inc. This material may be distributed only subject to the terms and conditions set forth in the Open Publication License, v1.0 or later (the latest version is presently available at

Distribution of substantively modified versions of this document is prohibited without the explicit permission of the copyright holder.

Distribution of the work or derivative of the work in any standard (paper) book form is prohibited unless prior permission is obtained from the copyright holder.