class Mutex

Mutex implements a simple semaphore that can be used to coordinate access to shared data from multiple concurrent threads.

Example:

require 'thread'
semaphore = Mutex.new

a = Thread.new {
  semaphore.synchronize {
    # access shared resource
  }
}

b = Thread.new {
  semaphore.synchronize {
    # access shared resource
  }
}

Public Instance Methods

exclusive_unlock { ... } click to toggle source

If the mutex is locked, unlocks the mutex, wakes one waiting thread, and yields in a critical section.

static VALUE
rb_mutex_exclusive_unlock(VALUE self)
{
    Mutex *mutex;
    VALUE waking;
    Data_Get_Struct(self, Mutex, mutex);

    waking = thread_exclusive(rb_mutex_exclusive_unlock_inner, (VALUE)mutex);

    if (!RTEST(waking)) {
        return Qnil;
    }

    run_thread(waking);

    return self;
}
lock click to toggle source

Attempts to grab the lock and waits if it isn't available.

static VALUE
rb_mutex_lock(VALUE self)
{
    Mutex *mutex;
    Data_Get_Struct(self, Mutex, mutex);
    lock_mutex(mutex);
    return self;
}
locked? click to toggle source

Returns true if this lock is currently held by some thread.

static VALUE
rb_mutex_locked_p(VALUE self)
{
    Mutex *mutex;
    Data_Get_Struct(self, Mutex, mutex);
    return MUTEX_LOCKED_P(mutex) ? Qtrue : Qfalse;
}
marshal_dump() click to toggle source
static VALUE
dummy_dump(VALUE self)
{
    return rb_str_new2("");
}
marshal_load(p1) click to toggle source

for marshalling mutexes and condvars

static VALUE
dummy_load(VALUE self, VALUE string)
{
    return Qnil;
}
synchronize { ... } click to toggle source

Obtains a lock, runs the block, and releases the lock when the block completes. See the example under Mutex.

static VALUE
rb_mutex_synchronize(VALUE self)
{
    rb_mutex_lock(self);
    return rb_ensure(rb_yield, Qundef, rb_mutex_unlock, self);
}
try_lock click to toggle source

Attempts to obtain the lock and returns immediately. Returns true if the lock was granted.

static VALUE
rb_mutex_try_lock(VALUE self)
{
    Mutex *mutex;

    Data_Get_Struct(self, Mutex, mutex);

    if (MUTEX_LOCKED_P(mutex))
        return Qfalse;

    mutex->owner = rb_thread_current();
    return Qtrue;
}
unlock() click to toggle source

Releases the lock. Returns nil if ref wasn't locked.

static VALUE
rb_mutex_unlock(VALUE self)
{
    Mutex *mutex;
    Data_Get_Struct(self, Mutex, mutex);

    if (RTEST(unlock_mutex(mutex))) {
        return self;
    } else {
        return Qnil;
    }
}