类 Monitor

当您想要为具有互斥的代码块创建锁对象时,请使用 Monitor 类。

require 'monitor'

lock = Monitor.new
lock.synchronize do
  # exclusive access
end

公共实例方法

enter() 点击切换源代码
static VALUE
monitor_enter(VALUE monitor)
{
    struct rb_monitor *mc = monitor_ptr(monitor);
    if (!mc_owner_p(mc)) {
        rb_mutex_lock(mc->mutex);
        RB_OBJ_WRITE(monitor, &mc->owner, rb_fiber_current());
        mc->count = 0;
    }
    mc->count++;
    return Qnil;
}
别名:mon_enter
exit() 点击切换源代码
static VALUE
monitor_exit(VALUE monitor)
{
    monitor_check_owner(monitor);

    struct rb_monitor *mc = monitor_ptr(monitor);

    if (mc->count <= 0) rb_bug("monitor_exit: count:%d", (int)mc->count);
    mc->count--;

    if (mc->count == 0) {
        RB_OBJ_WRITE(monitor, &mc->owner, Qnil);
        rb_mutex_unlock(mc->mutex);
    }
    return Qnil;
}
别名:mon_exit
mon_check_owner() 点击切换源代码
static VALUE
monitor_check_owner(VALUE monitor)
{
    struct rb_monitor *mc = monitor_ptr(monitor);
    if (!mc_owner_p(mc)) {
        rb_raise(rb_eThreadError, "current fiber not owner");
    }
    return Qnil;
}
mon_enter()
别名:enter
mon_exit()
别名:exit
mon_locked?() 点击切换源代码
static VALUE
monitor_locked_p(VALUE monitor)
{
    struct rb_monitor *mc = monitor_ptr(monitor);
    return rb_mutex_locked_p(mc->mutex);
}
mon_owned?() 点击切换源代码
static VALUE
monitor_owned_p(VALUE monitor)
{
    struct rb_monitor *mc = monitor_ptr(monitor);
    return (rb_mutex_locked_p(mc->mutex) && mc_owner_p(mc)) ? Qtrue : Qfalse;
}
mon_synchronize()
别名:synchronize
mon_try_enter()
别名:try_enter
new_cond() 点击切换源代码
# File monitor/lib/monitor.rb, line 257
def new_cond
  ::MonitorMixin::ConditionVariable.new(self)
end
synchronize() 点击切换源代码
static VALUE
monitor_synchronize(VALUE monitor)
{
    monitor_enter(monitor);
    return rb_ensure(monitor_sync_body, monitor, monitor_sync_ensure, monitor);
}
别名:mon_synchronize
try_enter() 点击切换源代码
static VALUE
monitor_try_enter(VALUE monitor)
{
    struct rb_monitor *mc = monitor_ptr(monitor);

    if (!mc_owner_p(mc)) {
        if (!rb_mutex_trylock(mc->mutex)) {
            return Qfalse;
        }
        RB_OBJ_WRITE(monitor, &mc->owner, rb_fiber_current());
        mc->count = 0;
    }
    mc->count += 1;
    return Qtrue;
}
try_mon_enter()

为了兼容性

别名:try_enter
wait_for_cond(p1, p2) 点击切换源代码
static VALUE
monitor_wait_for_cond(VALUE monitor, VALUE cond, VALUE timeout)
{
    VALUE count = monitor_exit_for_cond(monitor);
    struct wait_for_cond_data data = {
        monitor,
        cond,
        timeout,
        count,
    };

    return rb_ensure(monitor_wait_for_cond_body, (VALUE)&data,
                     monitor_enter_for_cond, (VALUE)&data);
}