class Thread::SizedQueue
此类表示具有指定大小容量的队列。如果容量已满,push 操作可能会被阻塞。
请参阅 Thread::Queue 以了解 Thread::SizedQueue 如何工作的示例。
Public Class Methods
Source
static VALUE
rb_szqueue_initialize(VALUE self, VALUE vmax)
{
long max;
struct rb_szqueue *sq = szqueue_ptr(self);
max = NUM2LONG(vmax);
if (max <= 0) {
rb_raise(rb_eArgError, "queue size must be positive");
}
RB_OBJ_WRITE(self, szqueue_list(sq), ary_buf_new());
ccan_list_head_init(szqueue_waitq(sq));
ccan_list_head_init(szqueue_pushq(sq));
sq->max = max;
return self;
}
创建一个最大容量为 max 的固定长度队列。
Public Instance Methods
Source
static VALUE
rb_szqueue_clear(VALUE self)
{
struct rb_szqueue *sq = szqueue_ptr(self);
rb_ary_clear(check_array(self, sq->q.que));
wakeup_all(szqueue_pushq(sq));
return self;
}
从队列中移除所有对象。
Source
static VALUE
rb_szqueue_close(VALUE self)
{
if (!queue_closed_p(self)) {
struct rb_szqueue *sq = szqueue_ptr(self);
FL_SET(self, QUEUE_CLOSED);
wakeup_all(szqueue_waitq(sq));
wakeup_all(szqueue_pushq(sq));
}
return self;
}
Source
static VALUE
rb_szqueue_max_get(VALUE self)
{
return LONG2NUM(szqueue_ptr(self)->max);
}
返回队列的最大大小。
Source
static VALUE
rb_szqueue_max_set(VALUE self, VALUE vmax)
{
long max = NUM2LONG(vmax);
long diff = 0;
struct rb_szqueue *sq = szqueue_ptr(self);
if (max <= 0) {
rb_raise(rb_eArgError, "queue size must be positive");
}
if (max > sq->max) {
diff = max - sq->max;
}
sq->max = max;
sync_wakeup(szqueue_pushq(sq), diff);
return vmax;
}
将队列的最大大小设置为给定的 number。
Source
static VALUE
rb_szqueue_num_waiting(VALUE self)
{
struct rb_szqueue *sq = szqueue_ptr(self);
return INT2NUM(sq->q.num_waiting + sq->num_waiting_push);
}
返回正在等待队列的线程数。
Source
# File thread_sync.rb, line 38 def pop(non_block = false, timeout: nil) if non_block && timeout raise ArgumentError, "can't set a timeout if non_block is enabled" end Primitive.rb_szqueue_pop(non_block, timeout) end
从队列中检索数据。
如果队列为空,则调用线程会挂起,直到有数据被推送到队列中。如果 non_block 为 true,线程不会挂起,并且会引发 ThreadError。
如果在 timeout 秒后没有可用数据,则返回 nil。如果 timeout 为 0,则立即返回。
Source
# File thread_sync.rb, line 61 def push(object, non_block = false, timeout: nil) if non_block && timeout raise ArgumentError, "can't set a timeout if non_block is enabled" end Primitive.rb_szqueue_push(object, non_block, timeout) end
将 object 推送到队列。
如果队列中没有剩余空间,则会等待直到有空间可用,除非 non_block 为 true。如果 non_block 为 true,线程不会挂起,并且会引发 ThreadError。
如果在 timeout 秒后没有可用空间,则返回 nil。如果 timeout 为 0,则立即返回。否则返回 self。