class Monitor - Documentation for Ruby 4.0
Description: class Monitor: Use the Monitor class when you want to have a lock object for blocks with mutual exclusion. require 'monitor' lock = Monitor.
Keywords: ruby,class,Monitor

🔍

No recent searches

# class Monitor

Use the `Monitor` class when you want to have a lock object for blocks with mutual exclusion.

    require 'monitor'

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

### Public Instance Methods

enter → nil
Source

    static VALUE
    monitor_enter(VALUE monitor)
    {
        struct monitor_args args;
        monitor_args_init(&args, monitor);
        monitor_enter0(&args);
        return Qnil;
    }

Enters exclusive section.

Also aliased as: mon_enter
exit → nil
Source

    static VALUE
    monitor_exit(VALUE monitor)
    {
        struct monitor_args args;
        monitor_args_init(&args, monitor);
        monitor_exit0(&args);
        return Qnil;
    }

Leaves exclusive section.

Also aliased as: mon_exit
mon_enter
Alias for: enter
mon_exit
Alias for: exit
mon_synchronize
Alias for: synchronize
mon_try_enter
Alias for: try_enter
new_cond ()
Source

    # File ext/monitor/lib/monitor.rb, line 263
    def new_cond
      ::MonitorMixin::ConditionVariable.new(self)
    end

Creates a new `MonitorMixin::ConditionVariable` associated with the `Monitor` object.

synchronize { } → result of the block
Source

    static VALUE
    monitor_synchronize(VALUE monitor)
    {
        struct monitor_args args;
        monitor_args_init(&args, monitor);
        monitor_enter0(&args);
        return rb_ensure(monitor_sync_body, (VALUE)&args, monitor_sync_ensure, (VALUE)&args);
    }

Enters exclusive section and executes the block. Leaves the exclusive section automatically when the block exits. See example under `MonitorMixin`.

Also aliased as: mon_synchronize
try_enter → true or false
Source

    static VALUE
    monitor_try_enter(VALUE monitor)
    {
        struct rb_monitor *mc = monitor_ptr(monitor);

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

Attempts to enter exclusive section. Returns `false` if lock fails.

Also aliased as: try_mon_enter, mon_try_enter
try_mon_enter
Alias for: try_enter