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

🔍

No recent searches

# class Thread::Monitor

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

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

Contrary to `Mutex`, `Monitor` is reentrant:

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

### Public Instance Methods

enter → nil
Source

    # File thread_sync.rb, line 572
    def enter
      Primitive.rb_monitor_enter
    end

Enters exclusive section.

exit → nil
Source

    # File thread_sync.rb, line 580
    def exit
      Primitive.rb_monitor_exit
    end

Leaves exclusive section.

new_cond ()
Source

    # File thread_sync.rb, line 605
    def new_cond
      ConditionVariable.new(self)
    end

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

synchronize { } → result of the block
Source

    # File thread_sync.rb, line 556
    def synchronize(&)
      Primitive.rb_monitor_synchronize
    end

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

try_enter → true or false
Source

    # File thread_sync.rb, line 564
    def try_enter
      Primitive.rb_monitor_try_enter
    end

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