Google

class Thread
Parent: Object
Version: 1.6

Index:

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

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 = Thread.new do
  puts  "In second thread"
  raise "Raise exception"
end
t1.join
print "not reached\n"

produces:

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
Thread.new { 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."

produces:

a a a no more a's will come out.

current Thread.current -> aThread
Returns the currently executing thread.

Thread.current -> #<Thread:0x401965c8 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 Thread::new.
kill Thread.kill( aThread )
Causes the given thread to exit (see Thread::exit).

count = 0
a = Thread.new { while true do  count += 1 end }
sleep(1) -> 1
Thread.kill(a) -> nil
count -> 921220
a.alive? -> false

list Thread.list -> anArray
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 }
l = Thread.list
l -> [#<Thread:0x4016ebcc sleep>, #<Thread:0x4018d824 run>, #<Thread:0x4018d860 sleep>, #<Thread:0x401965c8 run>]

main Thread.main -> aThread
Returns the main thread for the process.

Thread.main -> #<Thread:0x401965c8 run>

new Thread.new( [arg]* ) {| args | block } -> aThread
Creates a new thread to execute the instructions given in block, and begins running it. Any arguments passed to Thread::new are passed into the block.

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

produces:

abxyzc

pass Thread.pass
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

start Thread.start( [args]* ) {| args | block } -> aThread
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.
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 = Thread.new { print "a"; Thread.stop; print "c" }
Thread.pass
print "b"
a.run
a.join

produces:

abc

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.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| print x.inspect, x[:name], "\n" }

produces:

#<Thread:0x4018d540 sleep>C
#<Thread:0x4018d590 sleep>B
#<Thread:0x4018d5f4 sleep>A
#<Thread:0x401965c8 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 = 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

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 = 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 -> 655444
count2 -> 6285

raise thr.raise( anException )
Raises an exception (see Kernel::raise on page 424 for details) 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

run thr.run -> thr
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

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 = Thread.new { raise("die now") }
b = Thread.new { Thread.stop }
c = Thread.new { 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.new { 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 = Thread.new { 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.new { Thread.stop; puts "hey!" }
c.wakeup

produces:

hey!


Extracted from the book "Programming Ruby - The Pragmatic Programmer's Guide"
Copyright © 2000 Addison Wesley Longman, Inc. Released under the terms of the Open Publication License V1.0.
This reference is available for download.