Class: Thread

Inherits:
Object show all
Defined in:
vm.c,
vm.c

Overview

Threads are the Ruby implementation for a concurrent programming model.

Programs that require multiple threads of execution are a perfect candidate for Ruby’s Thread class.

For example, we can create a new thread separate from the main thread’s execution using ::new.

thr = Thread.new { puts "Whats the big deal" }

Then we are able to pause the execution of the main thread and allow our new thread to finish, using #join:

thr.join #=> "Whats the big deal"

If we don’t call thr.join before the main thread terminates, then all other threads including thr will be killed.

Alternatively, you can use an array for handling multiple threads at once, like in the following example:

threads = []
threads << Thread.new { puts "Whats the big deal" }
threads << Thread.new { 3.times { puts "Threads are fun!" } }

After creating a few threads we wait for them all to finish consecutively.

threads.each { |thr| thr.join }

Thread initialization

In order to create new threads, Ruby provides ::new, ::start, and ::fork. A block must be provided with each of these methods, otherwise a ThreadError will be raised.

When subclassing the Thread class, the initialize method of your subclass will be ignored by ::start and ::fork. Otherwise, be sure to call super in your initialize method.

=== Thread termination

For terminating threads, Ruby provides a variety of ways to do this.

The class method ::kill, is meant to exit a given thread:

thr = Thread.new { ... }
Thread.kill(thr) # sends exit() to thr

Alternatively, you can use the instance method #exit, or any of its aliases #kill or #terminate.

thr.exit

=== Thread status

Ruby provides a few instance methods for querying the state of a given thread. To get a string with the current thread’s state use #status

thr = Thread.new { sleep }
thr.status # => "sleep"
thr.exit
thr.status # => false

You can also use #alive? to tell if the thread is running or sleeping, and #stop? if the thread is dead or sleeping.

=== Thread variables and scope

Since threads are created with blocks, the same rules apply to other Ruby blocks for variable scope. Any local variables created within this block are accessible to only this thread.

==== Fiber-local vs. Thread-local

Each fiber has its own bucket for Thread#[] storage. When you set a new fiber-local it is only accessible within this Fiber. To illustrate:

Thread.new {
  Thread.current[:foo] = "bar"
  Fiber.new {
    p Thread.current[:foo] # => nil
  }.resume
}.join

This example uses #[] for getting and #[]= for setting fiber-locals, you can also use #keys to list the fiber-locals for a given thread and #key? to check if a fiber-local exists.

When it comes to thread-locals, they are accessible within the entire scope of the thread. Given the following example:

Thread.new{
  Thread.current.thread_variable_set(:foo, 1)
  p Thread.current.thread_variable_get(:foo) # => 1
  Fiber.new{

Thread.current.thread_variable_set(:foo, 2) p Thread.current.thread_variable_get(:foo) # => 2

     }.resume
     p Thread.current.thread_variable_get(:foo)   # => 2
   }.join

You can see that the thread-local +:foo+ carried over into the fiber
and was changed to +2+ by the end of the thread.

This example makes use of #thread_variable_set to create new
thread-locals, and #thread_variable_get to reference them.

There is also #thread_variables to list all thread-locals, and
#thread_variable? to check if a given thread-local exists.

=== Exception handling

Any thread can raise an exception using the #raise instance method, which operates similarly to Kernel#raise.

However, it’s important to note that an exception that occurs in any thread except the main thread depends on #abort_on_exception. This option is false by default, meaning that any unhandled exception will cause the thread to terminate silently when waited on by either #join or #value. You can change this default by either #abort_on_exception= true or setting $DEBUG to true.

With the addition of the class method ::handle_interrupt, you can now handle exceptions asynchronously with threads.

=== Scheduling

Ruby provides a few ways to support scheduling threads in your program.

The first way is by using the class method ::stop, to put the current running thread to sleep and schedule the execution of another thread.

Once a thread is asleep, you can use the instance method #wakeup to mark your thread as eligible for scheduling.

You can also try ::pass, which attempts to pass execution to another thread but is dependent on the OS whether a running thread will switch or not. The same goes for #priority, which lets you hint to the thread scheduler which threads you want to take precedence when passing execution. This method is also dependent on the OS and may be ignored on some platforms.

Direct Known Subclasses

Process::Waiter

Defined Under Namespace

Classes: Backtrace, Mutex

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(args) ⇒ Object

:nodoc:



771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
# File 'thread.c', line 771

static VALUE
thread_initialize(VALUE thread, VALUE args)
{
    rb_thread_t *th;
    if (!rb_block_given_p()) {
	rb_raise(rb_eThreadError, "must be called with a block");
    }
    GetThreadPtr(thread, th);
    if (th->first_args) {
	VALUE proc = th->first_proc, line, loc;
	VALUE file;
        if (!proc || !RTEST(loc = rb_proc_location(proc))) {
            rb_raise(rb_eThreadError, "already initialized thread");
        }
	file = RARRAY_AREF(loc, 0);
	if (NIL_P(line = RARRAY_AREF(loc, 1))) {
	    rb_raise(rb_eThreadError,
		     "already initialized thread - %"PRIsVALUE, file);
	}
        rb_raise(rb_eThreadError,
		 "already initialized thread - %"PRIsVALUE":%"PRIsVALUE,
                 file, line);
    }
    return thread_create_core(thread, args, 0);
}

Class Method Details

.abort_on_exceptionBoolean

Returns the status of the global “abort on exception” condition.

The default is false.

When set to true, all threads will abort (the process will exit(0)) if an exception is raised in any thread.

Can also be specified by the global $DEBUG flag or command line option -d.

See also ::abort_on_exception=.

There is also an instance level method to set this for a specific thread, see #abort_on_exception.

Returns:

  • (Boolean)


2488
2489
2490
2491
2492
# File 'thread.c', line 2488

static VALUE
rb_thread_s_abort_exc(void)
{
    return GET_THREAD()->vm->thread_abort_on_exception ? 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"

This will produce:

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

See also ::abort_on_exception.

There is also an instance level method to set this for a specific thread, see #abort_on_exception=.

Returns:

  • (Boolean)


2524
2525
2526
2527
2528
2529
# File 'thread.c', line 2524

static VALUE
rb_thread_s_abort_exc_set(VALUE self, VALUE val)
{
    GET_THREAD()->vm->thread_abort_on_exception = RTEST(val);
    return val;
}

.currentObject

Returns the currently executing thread.

Thread.current   #=> #<Thread:0x401bdf4c run>


2442
2443
2444
2445
2446
# File 'thread.c', line 2442

static VALUE
thread_s_current(VALUE klass)
{
    return rb_thread_current();
}

.DEBUGNumeric

Returns the thread debug level. Available only if compiled with THREAD_DEBUG=-1.

Returns:



238
239
240
241
242
# File 'thread.c', line 238

static VALUE
rb_thread_s_debug(void)
{
    return INT2NUM(rb_thread_debug_enabled);
}

.DEBUG=(num) ⇒ Object

Sets the thread debug level. Available only if compiled with THREAD_DEBUG=-1.



252
253
254
255
256
257
# File 'thread.c', line 252

static VALUE
rb_thread_s_debug_set(VALUE self, VALUE val)
{
    rb_thread_debug_enabled = RTEST(val) ? NUM2INT(val) : 0;
    return val;
}

.exitObject

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.



2280
2281
2282
2283
2284
2285
# File 'thread.c', line 2280

static VALUE
rb_thread_exit(void)
{
    rb_thread_t *th = GET_THREAD();
    return rb_thread_kill(th->self);
}

.start([args]) {|args| ... } ⇒ Object .fork([args]) {|args| ... } ⇒ Object

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

Overloads:

  • .start([args]) {|args| ... } ⇒ Object

    Yields:

    • (args)
  • .fork([args]) {|args| ... } ⇒ Object

    Yields:

    • (args)


764
765
766
767
768
# File 'thread.c', line 764

static VALUE
thread_start(VALUE klass, VALUE args)
{
    return thread_create_core(rb_thread_alloc(klass), args, 0);
}

.handle_interrupt(hash) { ... } ⇒ Object

Changes asynchronous interrupt timing.

interrupt means asynchronous event and corresponding procedure by Thread#raise, Thread#kill, signal trap (not supported yet) and main thread termination (if main thread terminates, then all other thread will be killed).

The given hash has pairs like ExceptionClass => :TimingSymbol. Where the ExceptionClass is the interrupt handled by the given block. The TimingSymbol can be one of the following symbols:

:immediate

Invoke interrupts immediately.

:on_blocking

Invoke interrupts while BlockingOperation.

:never

Never invoke all interrupts.

BlockingOperation means that the operation will block the calling thread, such as read and write. On CRuby implementation, BlockingOperation is any operation executed without GVL.

Masked asynchronous interrupts are delayed until they are enabled. This method is similar to sigprocmask(3).

NOTE

Asynchronous interrupts are difficult to use.

If you need to communicate between threads, please consider to use another way such as Queue.

Or use them with deep understanding about this method.

Usage

In this example, we can guard from Thread#raise exceptions.

Using the :never TimingSymbol the RuntimeError exception will always be ignored in the first block of the main thread. In the second ::handle_interrupt block we can purposefully handle RuntimeError exceptions.

th = Thread.new do
  Thread.handle_interrupt(RuntimeError => :never) {
    begin
      # You can write resource allocation code safely.
      Thread.handle_interrupt(RuntimeError => :immediate) {
   # ...
      }
    ensure
      # You can write resource deallocation code safely.
    end
  }
end
Thread.pass
# ...
th.raise "stop"

While we are ignoring the RuntimeError exception, it’s safe to write our resource allocation code. Then, the ensure block is where we can safely deallocate your resources.

Guarding from Timeout::Error

In the next example, we will guard from the Timeout::Error exception. This will help prevent from leaking resources when Timeout::Error exceptions occur during normal ensure clause. For this example we use the help of the standard library Timeout, from lib/timeout.rb

require 'timeout'
Thread.handle_interrupt(Timeout::Error => :never) {
  timeout(10){
    # Timeout::Error doesn't occur here
    Thread.handle_interrupt(Timeout::Error => :on_blocking) {
      # possible to be killed by Timeout::Error
      # while blocking operation
    }
    # Timeout::Error doesn't occur here
  }
}

In the first part of the timeout block, we can rely on Timeout::Error being ignored. Then in the Timeout::Error => :on_blocking block, any operation that will block the calling thread is susceptible to a Timeout::Error exception being raised.

Stack control settings

It’s possible to stack multiple levels of ::handle_interrupt blocks in order to control more than one ExceptionClass and TimingSymbol at a time.

Thread.handle_interrupt(FooError => :never) {
  Thread.handle_interrupt(BarError => :never) {
     # FooError and BarError are prohibited.
  }
}

Inheritance with ExceptionClass

All exceptions inherited from the ExceptionClass parameter will be considered.

Thread.handle_interrupt(Exception => :never) {
  # all exceptions inherited from Exception are prohibited.
}

Yields:



1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
# File 'thread.c', line 1808

static VALUE
rb_thread_s_handle_interrupt(VALUE self, VALUE mask_arg)
{
    VALUE mask;
    rb_thread_t *th = GET_THREAD();
    volatile VALUE r = Qnil;
    int state;

    if (!rb_block_given_p()) {
	rb_raise(rb_eArgError, "block is needed.");
    }

    mask = 0;
    mask_arg = rb_convert_type(mask_arg, T_HASH, "Hash", "to_hash");
    rb_hash_foreach(mask_arg, handle_interrupt_arg_check_i, (VALUE)&mask);
    if (!mask) {
	return rb_yield(Qnil);
    }
    OBJ_FREEZE_RAW(mask);
    rb_ary_push(th->pending_interrupt_mask_stack, mask);
    if (!rb_threadptr_pending_interrupt_empty_p(th)) {
	th->pending_interrupt_queue_checked = 0;
	RUBY_VM_SET_INTERRUPT(th);
    }

    TH_PUSH_TAG(th);
    if ((state = EXEC_TAG()) == 0) {
	r = rb_yield(Qnil);
    }
    TH_POP_TAG();

    rb_ary_pop(th->pending_interrupt_mask_stack);
    if (!rb_threadptr_pending_interrupt_empty_p(th)) {
	th->pending_interrupt_queue_checked = 0;
	RUBY_VM_SET_INTERRUPT(th);
    }

    RUBY_VM_CHECK_INTS(th);

    if (state) {
	JUMP_TAG(state);
    }

    return r;
}

.kill(thread) ⇒ Object

Causes the given thread to exit, see also 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


2261
2262
2263
2264
2265
# File 'thread.c', line 2261

static VALUE
rb_thread_s_kill(VALUE obj, VALUE th)
{
    return rb_thread_kill(th);
}

.listArray

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}

This will produce:

#<Thread:0x401b3e84 sleep>
#<Thread:0x401b3f38 run>
#<Thread:0x401b3fb0 sleep>
#<Thread:0x401bdf4c run>

Returns:



2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
# File 'thread.c', line 2407

VALUE
rb_thread_list(void)
{
    VALUE ary = rb_ary_new();
    rb_vm_t *vm = GET_THREAD()->vm;
    rb_thread_t *th = 0;

    list_for_each(&vm->living_threads, th, vmlt_node) {
	switch (th->status) {
	  case THREAD_RUNNABLE:
	  case THREAD_STOPPED:
	  case THREAD_STOPPED_FOREVER:
	    rb_ary_push(ary, th->self);
	  default:
	    break;
	}
    }
    return ary;
}

.mainObject

Returns the main thread.



2461
2462
2463
2464
2465
# File 'thread.c', line 2461

static VALUE
rb_thread_s_main(VALUE klass)
{
    return rb_thread_main();
}

.new(*args) ⇒ Object

Thread.new(*args, &proc) -> thread

Thread.new(*args) { |args| ... }	-> thread

Creates a new thread executing the given block.

Any +args+ given to ::new will be passed to the block:

arr = [] a, b, c = 1, 2, 3 Thread.new(a,b,c) { |d,e,f| arr << d << e << f }.join arr #=> [1, 2, 3]

A ThreadError exception is raised if ::new is called without a block.

If you're going to subclass Thread, be sure to call super in your
+initialize+ method, otherwise a ThreadError will be raised.


736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
# File 'thread.c', line 736

static VALUE
thread_s_new(int argc, VALUE *argv, VALUE klass)
{
    rb_thread_t *th;
    VALUE thread = rb_thread_alloc(klass);

    if (GET_VM()->main_thread->status == THREAD_KILLED)
	rb_raise(rb_eThreadError, "can't alloc thread");

    rb_obj_call_init(thread, argc, argv);
    GetThreadPtr(thread, th);
    if (!threadptr_initialized(th)) {
	rb_raise(rb_eThreadError, "uninitialized thread - check `%"PRIsVALUE"#initialize'",
		 klass);
    }
    return thread;
}

.passnil

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.

Returns:

  • (nil)


1526
1527
1528
1529
1530
1531
# File 'thread.c', line 1526

static VALUE
thread_s_pass(VALUE klass)
{
    rb_thread_schedule();
    return Qnil;
}

.pending_interrupt?(error = nil) ⇒ Boolean

Returns whether or not the asynchronous queue is empty.

Since Thread::handle_interrupt can be used to defer asynchronous events, this method can be used to determine if there are any deferred events.

If you find this method returns true, then you may finish :never blocks.

For example, the following method processes deferred asynchronous events immediately.

def Thread.kick_interrupt_immediately
  Thread.handle_interrupt(Object => :immediate) {
    Thread.pass
  }
end

If error is given, then check only for error type deferred events.

Usage

th = Thread.new{
  Thread.handle_interrupt(RuntimeError => :on_blocking){
    while true
      ...
      # reach safe point to invoke interrupt
      if Thread.pending_interrupt?
        Thread.handle_interrupt(Object => :immediate){}
      end
      ...
    end
  }
}
...
th.raise # stop thread

This example can also be written as the following, which you should use to avoid asynchronous interrupts.

flag = true
th = Thread.new{
  Thread.handle_interrupt(RuntimeError => :on_blocking){
    while true
      ...
      # reach safe point to invoke interrupt
      break if flag == false
      ...
    end
  }
}
...
flag = false # stop thread

Returns:

  • (Boolean)


1949
1950
1951
1952
1953
# File 'thread.c', line 1949

static VALUE
rb_thread_s_pending_interrupt_p(int argc, VALUE *argv, VALUE self)
{
    return rb_thread_pending_interrupt_p(argc, argv, GET_THREAD()->self);
}

.start([args]) {|args| ... } ⇒ Object .fork([args]) {|args| ... } ⇒ Object

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

Overloads:

  • .start([args]) {|args| ... } ⇒ Object

    Yields:

    • (args)
  • .fork([args]) {|args| ... } ⇒ Object

    Yields:

    • (args)


764
765
766
767
768
# File 'thread.c', line 764

static VALUE
thread_start(VALUE klass, VALUE args)
{
    return thread_create_core(rb_thread_alloc(klass), args, 0);
}

.stopnil

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
#=> "abc"

Returns:

  • (nil)


2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
# File 'thread.c', line 2374

VALUE
rb_thread_stop(void)
{
    if (rb_thread_alone()) {
	rb_raise(rb_eThreadError,
		 "stopping only thread\n\tnote: use sleep to stop forever");
    }
    rb_thread_sleep_deadly();
    return Qnil;
}

Instance Method Details

#[](sym) ⇒ Object?

Attribute Reference—Returns the value of a fiber-local variable (current thread’s root fiber if not explicitly inside a Fiber), 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

This will produce:

#<Thread:0x00000002a54220 dead>: A
#<Thread:0x00000002a541a8 dead>: B
#<Thread:0x00000002a54130 dead>: C

Thread#[] and Thread#[]= are not thread-local but fiber-local. This confusion did not exist in Ruby 1.8 because fibers are only available since Ruby 1.9. Ruby 1.9 chooses that the methods behaves fiber-local to save following idiom for dynamic scope.

def meth(newvalue)
  begin
    oldvalue = Thread.current[:name]
    Thread.current[:name] = newvalue
    yield
  ensure
    Thread.current[:name] = oldvalue
  end
end

The idiom may not work as dynamic scope if the methods are thread-local and a given block switches fiber.

f = Fiber.new {
  meth(1) {
    Fiber.yield
  }
}
meth(2) {
  f.resume
}
f.resume
p Thread.current[:name]
#=> nil if fiber-local
#=> 2 if thread-local (The value 2 is leaked to outside of meth method.)

For thread-local variables, please see #thread_variable_get and #thread_variable_set.

Returns:



2930
2931
2932
2933
2934
2935
2936
# File 'thread.c', line 2930

static VALUE
rb_thread_aref(VALUE thread, VALUE key)
{
    ID id = rb_check_id(&key);
    if (!id) return Qnil;
    return rb_thread_local_aref(thread, id);
}

#[]=(sym) ⇒ Object

Attribute Assignment—Sets or creates the value of a fiber-local variable, using either a symbol or a string.

See also Thread#[].

For thread-local variables, please see #thread_variable_set and #thread_variable_get.

Returns:



2985
2986
2987
2988
2989
# File 'thread.c', line 2985

static VALUE
rb_thread_aset(VALUE self, VALUE id, VALUE val)
{
    return rb_thread_local_aset(self, rb_to_id(id), val);
}

#abort_on_exceptionBoolean

Returns the status of the thread-local “abort on exception” condition for this thr.

The default is false.

See also #abort_on_exception=.

There is also a class level method to set this for all threads, see ::abort_on_exception.

Returns:

  • (Boolean)


2547
2548
2549
2550
2551
2552
2553
# File 'thread.c', line 2547

static VALUE
rb_thread_abort_exc(VALUE thread)
{
    rb_thread_t *th;
    GetThreadPtr(thread, th);
    return th->abort_on_exception ? Qtrue : Qfalse;
}

#abort_on_exception=(boolean) ⇒ Boolean

When set to true, all threads (including the main program) will abort if an exception is raised in this thr.

The process will effectively exit(0).

See also #abort_on_exception.

There is also a class level method to set this for all threads, see ::abort_on_exception=.

Returns:

  • (Boolean)


2571
2572
2573
2574
2575
2576
2577
2578
2579
# File 'thread.c', line 2571

static VALUE
rb_thread_abort_exc_set(VALUE thread, VALUE val)
{
    rb_thread_t *th;

    GetThreadPtr(thread, th);
    th->abort_on_exception = RTEST(val);
    return val;
}

#add_trace_func(proc) ⇒ Proc

Adds proc as a handler for tracing.

See Thread#set_trace_func and Kernel#set_trace_func.

Returns:



526
527
528
529
530
531
532
533
534
# File 'vm_trace.c', line 526

static VALUE
thread_add_trace_func_m(VALUE obj, VALUE trace)
{
    rb_thread_t *th;

    GetThreadPtr(obj, th);
    thread_add_trace_func(th, trace);
    return trace;
}

#alive?Boolean

Returns true if thr is running or sleeping.

thr = Thread.new { }
thr.join                #=> #<Thread:0x401b3fb0 dead>
Thread.current.alive?   #=> true
thr.alive?              #=> false

See also #stop? and #status.

Returns:

  • (Boolean)

Returns:

  • (Boolean)


2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
# File 'thread.c', line 2694

static VALUE
rb_thread_alive_p(VALUE thread)
{
    rb_thread_t *th;
    GetThreadPtr(thread, th);

    if (rb_threadptr_dead(th))
	return Qfalse;
    return Qtrue;
}

#backtraceArray

Returns the current backtrace of the target thread.

Returns:



4545
4546
4547
4548
4549
# File 'thread.c', line 4545

static VALUE
rb_thread_backtrace_m(int argc, VALUE *argv, VALUE thval)
{
    return rb_vm_thread_backtrace(argc, argv, thval);
}

#backtrace_locations(*args) ⇒ Object

Returns the execution stack for the target thread—an array containing backtrace location objects.

See Thread::Backtrace::Location for more information.

This method behaves similarly to Kernel#caller_locations except it applies to a specific thread.



4562
4563
4564
4565
4566
# File 'thread.c', line 4562

static VALUE
rb_thread_backtrace_locations_m(int argc, VALUE *argv, VALUE thval)
{
    return rb_vm_thread_backtrace_locations(argc, argv, thval);
}

#exitnil #killnil #terminatenil

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.

Overloads:

  • #exitnil

    Returns:

    • (nil)
  • #killnil

    Returns:

    • (nil)
  • #terminatenil

    Returns:

    • (nil)


2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
# File 'thread.c', line 2207

VALUE
rb_thread_kill(VALUE thread)
{
    rb_thread_t *th;

    GetThreadPtr(thread, th);

    if (th->to_kill || th->status == THREAD_KILLED) {
	return thread;
    }
    if (th == th->vm->main_thread) {
	rb_exit(EXIT_SUCCESS);
    }

    thread_debug("rb_thread_kill: %p (%"PRI_THREAD_ID")\n", (void *)th, thread_id_str(th));

    if (th == GET_THREAD()) {
	/* kill myself immediately */
	rb_threadptr_to_kill(th);
    }
    else {
	rb_threadptr_pending_interrupt_enque(th, eKillSignal);
	rb_threadptr_interrupt(th);
    }
    return thread;
}

#groupnil

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

Thread.main.group   #=> #<ThreadGroup:0x4029d914>

Returns:

  • (nil)


2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
# File 'thread.c', line 2592

VALUE
rb_thread_group(VALUE thread)
{
    rb_thread_t *th;
    VALUE group;
    GetThreadPtr(thread, th);
    group = th->thgroup;

    if (!group) {
	group = Qnil;
    }
    return group;
}

#inspectString

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

Returns:



2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
# File 'thread.c', line 2813

static VALUE
rb_thread_inspect(VALUE thread)
{
    VALUE cname = rb_class_path(rb_obj_class(thread));
    rb_thread_t *th;
    const char *status;
    VALUE str;

    GetThreadPtr(thread, th);
    status = thread_status_name(th);
    str = rb_sprintf("#<%"PRIsVALUE":%p", cname, (void *)thread);
    if (!NIL_P(th->name)) {
	rb_str_catf(str, "@%"PRIsVALUE, th->name);
    }
    if (!th->first_func && th->first_proc) {
	VALUE loc = rb_proc_location(th->first_proc);
	if (!NIL_P(loc)) {
	    const VALUE *ptr = RARRAY_CONST_PTR(loc);
	    rb_str_catf(str, "@%"PRIsVALUE":%"PRIsVALUE, ptr[0], ptr[1]);
	    rb_gc_force_recycle(loc);
	}
    }
    rb_str_catf(str, " %s>", status);
    OBJ_INFECT(str, thread);

    return str;
}

#joinObject #join(limit) ⇒ Object

The calling thread will suspend execution and run this thr.

Does not return until thr exits or until the given 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 or $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 thread x finish, thread a will be killed on exit.
#=> "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)

This will produce:

tick...
Waiting
tick...
Waiting
tick...
tick...


955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
# File 'thread.c', line 955

static VALUE
thread_join_m(int argc, VALUE *argv, VALUE self)
{
    rb_thread_t *target_th;
    double delay = DELAY_INFTY;
    VALUE limit;

    GetThreadPtr(self, target_th);

    rb_scan_args(argc, argv, "01", &limit);
    if (!NIL_P(limit)) {
	delay = rb_num2dbl(limit);
    }

    return thread_join(target_th, delay);
}

#key?(sym) ⇒ Boolean

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

me = Thread.current
me[:oliver] = "a"
me.key?(:oliver)    #=> true
me.key?(:stanley)   #=> false

Returns:

  • (Boolean)

Returns:

  • (Boolean)


3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
# File 'thread.c', line 3063

static VALUE
rb_thread_key_p(VALUE self, VALUE key)
{
    rb_thread_t *th;
    ID id = rb_check_id(&key);

    GetThreadPtr(self, th);

    if (!id || !th->local_storage) {
	return Qfalse;
    }
    if (st_lookup(th->local_storage, id, 0)) {
	return Qtrue;
    }
    return Qfalse;
}

#keysArray

Returns an array of the names of the fiber-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]

Returns:



3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
# File 'thread.c', line 3107

static VALUE
rb_thread_keys(VALUE self)
{
    rb_thread_t *th;
    VALUE ary = rb_ary_new();
    GetThreadPtr(self, th);

    if (th->local_storage) {
	st_foreach(th->local_storage, thread_keys_i, ary);
    }
    return ary;
}

#exitnil #killnil #terminatenil

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.

Overloads:

  • #exitnil

    Returns:

    • (nil)
  • #killnil

    Returns:

    • (nil)
  • #terminatenil

    Returns:

    • (nil)


2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
# File 'thread.c', line 2207

VALUE
rb_thread_kill(VALUE thread)
{
    rb_thread_t *th;

    GetThreadPtr(thread, th);

    if (th->to_kill || th->status == THREAD_KILLED) {
	return thread;
    }
    if (th == th->vm->main_thread) {
	rb_exit(EXIT_SUCCESS);
    }

    thread_debug("rb_thread_kill: %p (%"PRI_THREAD_ID")\n", (void *)th, thread_id_str(th));

    if (th == GET_THREAD()) {
	/* kill myself immediately */
	rb_threadptr_to_kill(th);
    }
    else {
	rb_threadptr_pending_interrupt_enque(th, eKillSignal);
	rb_threadptr_interrupt(th);
    }
    return thread;
}

#nameString

show the name of the thread.

Returns:



2760
2761
2762
2763
2764
2765
2766
# File 'thread.c', line 2760

static VALUE
rb_thread_getname(VALUE thread)
{
    rb_thread_t *th;
    GetThreadPtr(thread, th);
    return th->name;
}

#name=(name) ⇒ String

set given name to the ruby thread. On some platform, it may set the name to pthread and/or kernel.

Returns:



2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
# File 'thread.c', line 2776

static VALUE
rb_thread_setname(VALUE thread, VALUE name)
{
#ifdef SET_ANOTHER_THREAD_NAME
    const char *s = "";
#endif
    rb_thread_t *th;
    GetThreadPtr(thread, th);
    if (!NIL_P(name)) {
	rb_encoding *enc;
	StringValueCStr(name);
	enc = rb_enc_get(name);
	if (!rb_enc_asciicompat(enc)) {
	    rb_raise(rb_eArgError, "ASCII incompatible encoding (%s)",
		     rb_enc_name(enc));
	}
	name = rb_str_new_frozen(name);
#ifdef SET_ANOTHER_THREAD_NAME
	s = RSTRING_PTR(name);
#endif
    }
    th->name = name;
#if defined(SET_ANOTHER_THREAD_NAME)
    if (threadptr_initialized(th)) {
	SET_ANOTHER_THREAD_NAME(th->thread_id, s);
    }
#endif
    return name;
}

#pending_interrupt?(error = nil) ⇒ Boolean

Returns whether or not the asynchronous queue is empty for the target thread.

If error is given, then check only for error type deferred events.

See ::pending_interrupt? for more information.

Returns:

  • (Boolean)


1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
# File 'thread.c', line 1864

static VALUE
rb_thread_pending_interrupt_p(int argc, VALUE *argv, VALUE target_thread)
{
    rb_thread_t *target_th;

    GetThreadPtr(target_thread, target_th);

    if (rb_threadptr_pending_interrupt_empty_p(target_th)) {
	return Qfalse;
    }
    else {
	if (argc == 1) {
	    VALUE err;
	    rb_scan_args(argc, argv, "01", &err);
	    if (!rb_obj_is_kind_of(err, rb_cModule)) {
		rb_raise(rb_eTypeError, "class or module required for rescue clause");
	    }
	    if (rb_threadptr_pending_interrupt_include_p(target_th, err)) {
		return Qtrue;
	    }
	    else {
		return Qfalse;
	    }
	}
	return Qtrue;
    }
}

#priorityInteger

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

Returns:



3208
3209
3210
3211
3212
3213
3214
# File 'thread.c', line 3208

static VALUE
rb_thread_priority(VALUE thread)
{
    rb_thread_t *th;
    GetThreadPtr(thread, th);
    return INT2NUM(th->priority);
}

#priority=(integer) ⇒ Object

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


3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
# File 'thread.c', line 3243

static VALUE
rb_thread_priority_set(VALUE thread, VALUE prio)
{
    rb_thread_t *th;
    int priority;
    GetThreadPtr(thread, th);


#if USE_NATIVE_THREAD_PRIORITY
    th->priority = NUM2INT(prio);
    native_thread_apply_priority(th);
#else
    priority = NUM2INT(prio);
    if (priority > RUBY_THREAD_PRIORITY_MAX) {
	priority = RUBY_THREAD_PRIORITY_MAX;
    }
    else if (priority < RUBY_THREAD_PRIORITY_MIN) {
	priority = RUBY_THREAD_PRIORITY_MIN;
    }
    th->priority = priority;
#endif
    return INT2NUM(th->priority);
}

#raiseObject #raise(string) ⇒ Object #raise(exception[, string [, array]]) ⇒ Object

Raises an exception from the given thread. The caller does not have to be thr. See Kernel#raise for more information.

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

This will produce:

prog.rb:3: Gotcha (RuntimeError)
	from prog.rb:2:in `initialize'
	from prog.rb:2:in `new'
	from prog.rb:2


2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
# File 'thread.c', line 2178

static VALUE
thread_raise_m(int argc, VALUE *argv, VALUE self)
{
    rb_thread_t *target_th;
    rb_thread_t *th = GET_THREAD();
    GetThreadPtr(self, target_th);
    rb_threadptr_raise(target_th, argc, argv);

    /* To perform Thread.current.raise as Kernel.raise */
    if (th == target_th) {
	RUBY_VM_CHECK_INTS(th);
    }
    return Qnil;
}

#runObject

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

This will produce:

a
Got here
c

See also the instance method #wakeup.



2350
2351
2352
2353
2354
2355
2356
# File 'thread.c', line 2350

VALUE
rb_thread_run(VALUE thread)
{
    rb_thread_wakeup(thread);
    rb_thread_schedule();
    return thread;
}

#safe_levelInteger

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 = 1; sleep }
Thread.current.safe_level   #=> 0
thr.safe_level              #=> 1

Returns:



2744
2745
2746
2747
2748
2749
2750
2751
# File 'thread.c', line 2744

static VALUE
rb_thread_safe_level(VALUE thread)
{
    rb_thread_t *th;
    GetThreadPtr(thread, th);

    return INT2NUM(th->safe_level);
}

#set_trace_func(proc) ⇒ Proc #set_trace_func(nil) ⇒ nil

Establishes proc on thr as the handler for tracing, or disables tracing if the parameter is nil.

See Kernel#set_trace_func.

Overloads:

  • #set_trace_func(proc) ⇒ Proc

    Returns:

  • #set_trace_func(nil) ⇒ nil

    Returns:

    • (nil)


547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
# File 'vm_trace.c', line 547

static VALUE
thread_set_trace_func_m(VALUE obj, VALUE trace)
{
    rb_thread_t *th;

    GetThreadPtr(obj, th);
    rb_threadptr_remove_event_hook(th, call_trace_func, Qundef);

    if (NIL_P(trace)) {
	return Qnil;
    }

    thread_add_trace_func(th, trace);
    return trace;
}

#statusString, ...

Returns the status of thr.

"sleep"

Returned if this thread is sleeping or waiting on I/O

"run"

When this thread is executing

"aborting"

If this thread is aborting

false

When this thread is terminated normally

nil

If 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"

See also the instance methods #alive? and #stop?

Returns:



2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
# File 'thread.c', line 2663

static VALUE
rb_thread_status(VALUE thread)
{
    rb_thread_t *th;
    GetThreadPtr(thread, th);

    if (rb_threadptr_dead(th)) {
	if (!NIL_P(th->errinfo) && !FIXNUM_P(th->errinfo)
	    /* TODO */ ) {
	    return Qnil;
	}
	return Qfalse;
    }
    return rb_str_new2(thread_status_name(th));
}

#stop?Boolean

Returns true if thr is dead or sleeping.

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

See also #alive? and #status.

Returns:

  • (Boolean)

Returns:

  • (Boolean)


2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
# File 'thread.c', line 2719

static VALUE
rb_thread_stop_p(VALUE thread)
{
    rb_thread_t *th;
    GetThreadPtr(thread, th);

    if (rb_threadptr_dead(th))
	return Qtrue;
    if (th->status == THREAD_STOPPED || th->status == THREAD_STOPPED_FOREVER)
	return Qtrue;
    return Qfalse;
}

#exitnil #killnil #terminatenil

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.

Overloads:

  • #exitnil

    Returns:

    • (nil)
  • #killnil

    Returns:

    • (nil)
  • #terminatenil

    Returns:

    • (nil)


2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
# File 'thread.c', line 2207

VALUE
rb_thread_kill(VALUE thread)
{
    rb_thread_t *th;

    GetThreadPtr(thread, th);

    if (th->to_kill || th->status == THREAD_KILLED) {
	return thread;
    }
    if (th == th->vm->main_thread) {
	rb_exit(EXIT_SUCCESS);
    }

    thread_debug("rb_thread_kill: %p (%"PRI_THREAD_ID")\n", (void *)th, thread_id_str(th));

    if (th == GET_THREAD()) {
	/* kill myself immediately */
	rb_threadptr_to_kill(th);
    }
    else {
	rb_threadptr_pending_interrupt_enque(th, eKillSignal);
	rb_threadptr_interrupt(th);
    }
    return thread;
}

#thread_variable?(key) ⇒ Boolean

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

me = Thread.current
me.thread_variable_set(:oliver, "a")
me.thread_variable?(:oliver)    #=> true
me.thread_variable?(:stanley)   #=> false

Note that these are not fiber local variables. Please see Thread#[] and Thread#thread_variable_get for more details.

Returns:

  • (Boolean)

Returns:

  • (Boolean)


3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
# File 'thread.c', line 3173

static VALUE
rb_thread_variable_p(VALUE thread, VALUE key)
{
    VALUE locals;
    ID id = rb_check_id(&key);

    if (!id) return Qfalse;

    locals = rb_ivar_get(thread, id_locals);

    if (!RHASH(locals)->ntbl)
        return Qfalse;

    if (st_lookup(RHASH(locals)->ntbl, ID2SYM(id), 0)) {
	return Qtrue;
    }

    return Qfalse;
}

#thread_variable_get(key) ⇒ Object?

Returns the value of a thread local variable that has been set. Note that these are different than fiber local values. For fiber local values, please see Thread#[] and Thread#[]=.

Thread local values are carried along with threads, and do not respect fibers. For example:

Thread.new {
  Thread.current.thread_variable_set("foo", "bar") # set a thread local
  Thread.current["foo"] = "bar"                    # set a fiber local

  Fiber.new {
    Fiber.yield [
      Thread.current.thread_variable_get("foo"), # get the thread local
      Thread.current["foo"],                     # get the fiber local
    ]
  }.resume
}.join.value # => ['bar', nil]

The value “bar” is returned for the thread local, where nil is returned for the fiber local. The fiber is executed in the same thread, so the thread local values are available.

Returns:



3019
3020
3021
3022
3023
3024
3025
3026
# File 'thread.c', line 3019

static VALUE
rb_thread_variable_get(VALUE thread, VALUE key)
{
    VALUE locals;

    locals = rb_ivar_get(thread, id_locals);
    return rb_hash_aref(locals, rb_to_symbol(key));
}

#thread_variable_set(key, value) ⇒ Object

Sets a thread local with key to value. Note that these are local to threads, and not to fibers. Please see Thread#thread_variable_get and Thread#[] for more information.



3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
# File 'thread.c', line 3037

static VALUE
rb_thread_variable_set(VALUE thread, VALUE id, VALUE val)
{
    VALUE locals;

    if (OBJ_FROZEN(thread)) {
	rb_error_frozen("thread locals");
    }

    locals = rb_ivar_get(thread, id_locals);
    return rb_hash_aset(locals, rb_to_symbol(id), val);
}

#thread_variablesArray

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

thr = Thread.new do
  Thread.current.thread_variable_set(:cat, 'meow')
  Thread.current.thread_variable_set("dog", 'woof')
end
thr.join               #=> #<Thread:0x401b3f10 dead>
thr.thread_variables   #=> [:dog, :cat]

Note that these are not fiber local variables. Please see Thread#[] and Thread#thread_variable_get for more details.

Returns:



3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
# File 'thread.c', line 3144

static VALUE
rb_thread_variables(VALUE thread)
{
    VALUE locals;
    VALUE ary;

    locals = rb_ivar_get(thread, id_locals);
    ary = rb_ary_new();
    rb_hash_foreach(locals, keys_i, ary);

    return ary;
}

#valueObject

Waits for thr to complete, using #join, and returns its value or raises the exception which terminated the thread.

a = Thread.new { 2 + 2 }
a.value   #=> 4

b = Thread.new { raise 'something went wrong' }
b.value   #=> RuntimeError: something went wrong

Returns:



986
987
988
989
990
991
992
993
# File 'thread.c', line 986

static VALUE
thread_value(VALUE self)
{
    rb_thread_t *th;
    GetThreadPtr(self, th);
    thread_join(th, DELAY_INFTY);
    return th->value;
}

#wakeupObject

Marks a given thread as eligible for scheduling, however it may still remain blocked on I/O.

Note: This does not invoke the scheduler, see #run for more information.

c = Thread.new { Thread.stop; puts "hey!" }
sleep 0.1 while c.status!='sleep'
c.wakeup
c.join
#=> "hey!"


2304
2305
2306
2307
2308
2309
2310
2311
# File 'thread.c', line 2304

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