Ruby 2.4

ConditionVariable

class ConditionVariable

Parent:Object

ConditionVariable对象增加类互斥量。使用条件变量,可以在临界区中间挂起,直到资源可用。

Example:

require 'thread' mutex = Mutex.new resource = ConditionVariable.new a = Thread.new { mutex.synchronize { # Thread 'a' now needs the resource resource.wait(mutex) # 'a' can now have the resource } } b = Thread.new { mutex.synchronize { # Thread 'b' has finished using the resource resource.signal } }

公共类方法

new() Show source

创建一个新的条件变量实例。

static VALUE rb_condvar_initialize(VALUE self) { RSTRUCT_SET(self, CONDVAR_WAITERS, ary_buf_new() return self; }

公共实例方法

broadcast() Show source

唤醒等待这个锁的所有线程。

static VALUE rb_condvar_broadcast(VALUE self) { wakeup_all_threads(GET_CONDVAR_WAITERS(self) return self; }

signal() Show source

唤醒第一个线程等待这个锁。

static VALUE rb_condvar_signal(VALUE self) { wakeup_first_thread(GET_CONDVAR_WAITERS(self) return self; }

wait(mutex, timeout=nil) Show source

释放锁定mutex并等待; 重新获得唤醒时的锁定。

如果timeout给出,timeout即使没有其他线程不发送信号,该方法在秒数后返回。

static VALUE rb_condvar_wait(int argc, VALUE *argv, VALUE self) { VALUE waiters = GET_CONDVAR_WAITERS(self VALUE mutex, timeout; struct sleep_call args; rb_scan_args(argc, argv, "11", &mutex, &timeout args.mutex = mutex; args.timeout = timeout; rb_ary_push(waiters, rb_thread_current() rb_ensure(do_sleep, (VALUE)&args, delete_current_thread, waiters return self; }