Class: Thread
Overview
Class Method Summary (collapse)
-
+ abort_on_exception
Returns the status of the global "abort on exception" condition.
-
+ abort_on_exception=
When set to true, all threads will abort if an exception is raised.
-
+ alloc
:nodoc:.
-
+ current
Returns the currently executing thread.
-
+ exit
Terminates the currently running thread and schedules another thread to be run.
-
+ fork
Basically the same as Thread::new.
-
+ kill
Causes the given thread to exit (see Thread::exit).
-
+ list
Returns an array of Thread objects for all threads that are either runnable or stopped.
-
+ main
Returns the main thread.
-
+ pass
Give the thread scheduler a hint to pass execution to another thread.
-
+ start
Basically the same as Thread::new.
-
+ stop
Stops execution of the current thread, putting it into a "sleep" state, and schedules execution of another thread.
Instance Method Summary (collapse)
-
- []
Attribute Reference---Returns the value of a thread-local variable, using either a symbol or a string name.
-
- []=
Attribute Assignment---Sets or creates the value of a thread-local variable, using either a symbol or a string.
-
- abort_on_exception
Returns the status of the thread-local "abort on exception" condition for thr.
-
- abort_on_exception=
When set to true, causes all threads (including the main program) to abort if an exception is raised in thr.
-
- alive?
Returns true if thr is running or sleeping.
-
- exit
Terminates thr and schedules another thread to be run.
-
- group
Returns the ThreadGroup which contains thr, or nil if the thread is not a member of any group.
-
- initialize
constructor
:nodoc:.
-
- inspect
Dump the name, id, and status of thr to a string.
-
- join
The calling thread will suspend execution and run thr.
-
- key?
Returns true if the given string (or symbol) exists as a thread-local variable.
-
- keys
Returns an an array of the names of the thread-local variables (as Symbols).
-
- kill
Terminates thr and schedules another thread to be run.
-
- priority
Returns the priority of thr.
-
- priority=
Sets the priority of thr to integer.
-
- raise
Raises an exception (see Kernel::raise) from thr.
-
- run
Wakes up thr, making it eligible for scheduling.
-
- safe_level
Returns the safe level in effect for thr.
-
- status
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.
-
- stop?
Returns true if thr is dead or sleeping.
-
- terminate
Terminates thr and schedules another thread to be run.
-
- value
Waits for thr to complete (via Thread#join) and returns its value.
-
- wakeup
Marks thr as eligible for scheduling (it may still remain blocked on I/O, however).
Methods inherited from NSObject
#!, #!=, #!~, #, #==, #===, #=~, #Rational, #__callee__, #__method__, #__send__, #__type__, `, allocWithZone:, #autoContentAccessingProxy, autoload, autoload?, autorelease_pool, #awakeAfterUsingCoder:, binding, block_given?, caller, cancelPreviousPerformRequestsWithTarget:, cancelPreviousPerformRequestsWithTarget:selector:object:, catch, class, classFallbacksForKeyedArchiver, #classForCoder, #classForKeyedArchiver, classForKeyedUnarchiver, #clone, conformsToProtocol:, #copy, copyWithZone:, #dealloc, #define_singleton_method, description, display, #doesNotRecognizeSelector:, #dup, #enum_for, #eql?, #equal?, #extend, fail, #finalize, format, #forwardInvocation:, #forwardingTargetForSelector:, framework, #freeze, #frozen?, getpass, gets, global_variables, #init, initialize, #initialize_clone, #initialize_copy, #initialize_dup, instanceMethodForSelector:, instanceMethodSignatureForSelector:, #instance_eval, #instance_exec, #instance_of?, #instance_variable_defined?, #instance_variable_get, #instance_variable_set, #instance_variables, instancesRespondToSelector:, isSubclassOfClass:, #is_a?, iterator?, #kind_of?, lambda, load, load_bridge_support_file, load_plist, local_variables, loop, #method, #methodForSelector:, #methodSignatureForSelector:, #methods, #mutableCopy, mutableCopyWithZone:, new, #nil?, open, p, #performSelector:onThread:withObject:waitUntilDone:, #performSelector:onThread:withObject:waitUntilDone:modes:, #performSelector:withObject:afterDelay:, #performSelector:withObject:afterDelay:inModes:, #performSelectorInBackground:withObject:, #performSelectorOnMainThread:withObject:waitUntilDone:, #performSelectorOnMainThread:withObject:waitUntilDone:modes:, print, printf, #private_methods, proc, #protected_methods, #public_method, #public_methods, #public_send, putc, puts, raise, rand, readline, readlines, #replacementObjectForCoder:, #replacementObjectForKeyedArchiver:, require, resolveClassMethod:, resolveInstanceMethod:, #respond_to?, #respond_to_missing?, select, #send, setVersion:, #singleton_methods, sprintf, srand, superclass, #taint, #tainted?, #tap, test, throw, #to_plist, #to_s, trace_var, trap, #trust, #untaint, untrace_var, #untrust, #untrusted?, version
Constructor Details
- (Object) initialize
:nodoc:
Dynamic Method Handling
This class handles dynamic methods through the method_missing method in the class NSObject
Class Method Details
+ (Boolean) abort_on_exception
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=.
+ (Boolean) abort_on_exception=(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
+ (Object) alloc
:nodoc:
+ (Thread) current
Returns the currently executing thread.
Thread.current #=> #<Thread:0x401bdf4c run>
+ (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.
+ (Thread) kill(thread)
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
+ (Array) list
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>
+ (Thread) main
Returns the main thread.
+ (nil) pass
Give the thread scheduler a hint to pass execution to another thread. A running thread may or may not switch, it depends on OS and processor.
+ (nil) stop
Stops execution of the current thread, putting it into a "sleep" state, and schedules execution of another thread.
a = Thread.new { print "a"; Thread.stop; print "c" }
sleep 0.1 while a.status!='sleep'
print "b"
a.run
a.join
produces:
abc
Instance Method Details
- (Object?) [](sym)
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.
[
Thread.new { Thread.current["name"] = "A" },
Thread.new { Thread.current[:name] = "B" },
Thread.new { Thread.current["name"] = "C" }
].each do |th|
th.join
puts "#{th.inspect}: #{th[:name]}"
end
produces:
#<Thread:0x00000002a54220 dead>: A
#<Thread:0x00000002a541a8 dead>: B
#<Thread:0x00000002a54130 dead>: C
- (Object) []=(sym)
Attribute Assignment---Sets or creates the value of a thread-local variable, using either a symbol or a string. See also Thread#[].
- (Boolean) abort_on_exception
Returns the status of the thread-local "abort on exception" condition for thr. The default is false. See also Thread::abort_on_exception=.
- (Boolean) abort_on_exception=(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).
- (Boolean) alive?
Returns true if thr is running or sleeping.
thr = Thread.new { }
thr.join #=> #<Thread:0x401b3fb0 dead>
Thread.current.alive? #=> true
thr.alive? #=> false
- (Thread?) exit - (Thread?) kill - (Thread?) terminate
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.
- (ThreadGroup?) group
Returns the ThreadGroup which contains thr, or nil if the thread is not a member of any group.
Thread.main.group #=> #<ThreadGroup:0x4029d914>
- (String) inspect
Dump the name, id, and status of thr to a string.
- (Thread) join - (Thread) join(limit)
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...
- (Boolean) key?(sym)
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
- (Array) keys
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]
- (Thread?) exit - (Thread?) kill - (Thread?) terminate
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.
- (Integer) priority
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 thread will run more frequently than lower-priority threads (but lower-priority threads can also run).
This is just hint for Ruby thread scheduler. It may be ignored on some platform.
Thread.current.priority #=> 0
- (Thread) priority=(integer)
Sets the priority of thr to integer. Higher-priority threads will run more frequently than lower-priority threads (but lower-priority threads can also run).
This is just hint for Ruby thread scheduler. It may be ignored on some platform.
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
count1 #=> 622504
count2 #=> 5832
- (Object) raise - (Object) raise(string) - (Object) raise(exception[, string [, array]])
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
- (Thread) run
Wakes up thr, making it eligible for scheduling.
a = Thread.new { puts "a"; Thread.stop; puts "c" }
sleep 0.1 while a.status!='sleep'
puts "Got here"
a.run
a.join
produces:
a
Got here
c
- (Integer) safe_level
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
- (String, ...) status
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 }
d.kill #=> #<Thread:0x401b3678 aborting>
a.status #=> nil
b.status #=> "sleep"
c.status #=> false
d.status #=> "aborting"
Thread.current.status #=> "run"
- (Boolean) stop?
Returns true if thr is dead or sleeping.
a = Thread.new { Thread.stop }
b = Thread.current
a.stop? #=> true
b.stop? #=> false
- (Thread?) exit - (Thread?) kill - (Thread?) terminate
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.