類別 ThreadGroup

ThreadGroup 提供一種方法,可以將多個執行緒追蹤為一個群組。

一個給定的 Thread 物件一次只能屬於一個 ThreadGroup;將執行緒新增至新的群組會將其從任何先前群組中移除。

新建立的執行緒屬於與建立它們的執行緒相同的群組。

常數

Default

Ruby 啟動時建立的預設 ThreadGroup;所有執行緒預設都屬於它。

公開實例方法

add(thread) → thgrp 按一下以切換來源

將指定的 thread 新增至這個群組,並將其從它先前可能已成為成員的任何其他群組中移除。

puts "Initial group is #{ThreadGroup::Default.list}"
tg = ThreadGroup.new
t1 = Thread.new { sleep }
t2 = Thread.new { sleep }
puts "t1 is #{t1}"
puts "t2 is #{t2}"
tg.add(t1)
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>
static VALUE
thgroup_add(VALUE group, VALUE thread)
{
    rb_thread_t *target_th = rb_thread_ptr(thread);
    struct thgroup *data;

    if (OBJ_FROZEN(group)) {
        rb_raise(rb_eThreadError, "can't move to the frozen thread group");
    }
    TypedData_Get_Struct(group, struct thgroup, &thgroup_data_type, data);
    if (data->enclosed) {
        rb_raise(rb_eThreadError, "can't move to the enclosed thread group");
    }

    if (OBJ_FROZEN(target_th->thgroup)) {
        rb_raise(rb_eThreadError, "can't move from the frozen thread group");
    }
    TypedData_Get_Struct(target_th->thgroup, struct thgroup, &thgroup_data_type, data);
    if (data->enclosed) {
        rb_raise(rb_eThreadError,
                 "can't move from the enclosed thread group");
    }

    target_th->thgroup = group;
    return group;
}
enclose → thgrp 按一下以切換來源

防止將執行緒新增至接收的 ThreadGroup 或從中移除執行緒。

仍可以在封閉的 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
static VALUE
thgroup_enclose(VALUE group)
{
    struct thgroup *data;

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

    return group;
}
enclosed? → true 或 false 按一下以切換來源

如果 thgrp 已封閉,則傳回 true。另請參閱 ThreadGroup#enclose

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

    TypedData_Get_Struct(group, struct thgroup, &thgroup_data_type, data);
    return RBOOL(data->enclosed);
}
list → 陣列 按一下以切換來源

傳回屬於這個群組的所有現有 Thread 物件的陣列。

ThreadGroup::Default.list   #=> [#<Thread:0x401bdf4c run>]
static VALUE
thgroup_list(VALUE group)
{
    VALUE ary = rb_ary_new();
    rb_thread_t *th = 0;
    rb_ractor_t *r = GET_RACTOR();

    ccan_list_for_each(&r->threads.set, th, lt_node) {
        if (th->thgroup == group) {
            rb_ary_push(ary, th->self);
        }
    }
    return ary;
}