类 ThreadGroup
ThreadGroup
提供了一种将多个线程作为一组进行跟踪的方法。
给定的 Thread
对象只能属于一个 ThreadGroup
,一次将线程添加到新组会将其从任何以前的组中删除。
新创建的线程属于与创建它们的线程相同的组。
常量
- 默认
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 → array 点击切换源代码
返回属于此组的所有现有 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; }