Class: ThreadGroup

Object show all
Defined in:


ThreadGroup provides a means of keeping track of a number of threads as a group. A Thread can belong to only one ThreadGroup at a time; adding a thread to a new group will remove it from any previous group.

Newly created threads belong to the same group as the thread from which they were created.

Constant Summary collapse

Default =

Instance Method Summary collapse

Instance Method Details

#add(thread) ⇒ Object

Adds the given thread to this group, removing it from any other group to which it may have previously belonged.

puts "Initial group is #{ThreadGroup::Default.list}"
tg =
t1 = { sleep }
t2 = { sleep }
puts "t1 is #{t1}"
puts "t2 is #{t2}"
puts "Initial group now #{ThreadGroup::Default.list}"
puts "tg group now #{tg.list}"


Initial group is #<Thread:0x401bdf4c>
t1 is #<Thread:0x401b3c90>
t2 is #<Thread:0x401b3c18>
Initial group now #<Thread:0x401b3c18>#<Thread:0x401bdf4c>
tg group now #<Thread:0x401b3c90>

# File 'thread.c'

static VALUE
thgroup_add(VALUE group, VALUE thread)
rb_thread_t *th;
struct thgroup *data;

GetThreadPtr(thread, th);

if (OBJ_FROZEN(group)) {
rb_raise(rb_eThreadError, "can't move to the frozen thread group");


Prevents threads from being added to or removed from the receiving ThreadGroup. New threads can still be started in an enclosed ThreadGroup.

ThreadGroup::Default.enclose        #=> #<ThreadGroup:0x4029d914>
thr = Thread::new { Thread.stop }   #=> #<Thread:0x402a7210 sleep>
tg = ThreadGroup::new               #=> #<ThreadGroup:0x402752d4>
tg.add thr


ThreadError: can't move from the enclosed thread group

# File 'thread.c'

static VALUE
thgroup_enclose(VALUE group)
    struct thgroup *data;

    TypedData_Get_Struct(group, struct thgroup, &thgroup_data_type, data);
    data->enclosed = 1;

    return group;


Returns true if thgrp is enclosed. See also ThreadGroup#enclose.


  • (Boolean)

# File 'thread.c'

static VALUE
thgroup_enclosed_p(VALUE group)
    struct thgroup *data;

    TypedData_Get_Struct(group, struct thgroup, &thgroup_data_type, data);
    if (data->enclosed)
    return Qtrue;
    return Qfalse;


Returns an array of all existing Thread objects that belong to this group.

ThreadGroup::Default.list   #=> [#<Thread:0x401bdf4c run>]


# File 'thread.c'

static VALUE
thgroup_list(VALUE group)
    VALUE ary = rb_ary_new();
    struct thgroup_list_params param;

    param.ary = ary; = group;
    st_foreach(GET_THREAD()->vm->living_threads, thgroup_list_i, (st_data_t) & param);
    return ary;