Class: ConditionVariable

Inherits:
Object show all
Defined in:
thread_sync.c,
thread_sync.c

Overview

ConditionVariable objects augment class Mutex. Using condition variables, it is possible to suspend while in the middle of a critical section until a resource becomes available.

Example:

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

}

Instance Method Summary collapse

Constructor Details

#initializeObject

Creates a new condition variable instance.


1355
1356
1357
1358
1359
1360
1361
# File 'thread_sync.c', line 1355

static VALUE
rb_condvar_initialize(VALUE self)
{
    struct rb_condvar *cv = condvar_ptr(self);
    list_head_init(&cv->waitq);
    return self;
}

Instance Method Details

#broadcastObject

Wakes up all threads waiting for this lock.


1432
1433
1434
1435
1436
1437
1438
# File 'thread_sync.c', line 1432

static VALUE
rb_condvar_broadcast(VALUE self)
{
    struct rb_condvar *cv = condvar_ptr(self);
    wakeup_all(&cv->waitq);
    return self;
}

#marshal_dumpObject

:nodoc:


1441
1442
1443
1444
1445
1446
# File 'thread_sync.c', line 1441

static VALUE
undumpable(VALUE obj)
{
    rb_raise(rb_eTypeError, "can't dump %"PRIsVALUE, rb_obj_class(obj));
    UNREACHABLE_RETURN(Qnil);
}

#signalObject

Wakes up the first thread in line waiting for this lock.


1418
1419
1420
1421
1422
1423
1424
# File 'thread_sync.c', line 1418

static VALUE
rb_condvar_signal(VALUE self)
{
    struct rb_condvar *cv = condvar_ptr(self);
    wakeup_one(&cv->waitq);
    return self;
}

#wait(mutex, timeout = nil) ⇒ Object

Releases the lock held in mutex and waits; reacquires the lock on wakeup.

If timeout is given, this method returns after timeout seconds passed, even if no other thread doesn't signal.


1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
# File 'thread_sync.c', line 1396

static VALUE
rb_condvar_wait(int argc, VALUE *argv, VALUE self)
{
    struct rb_condvar *cv = condvar_ptr(self);
    struct sleep_call args;
    struct sync_waiter w;

    rb_scan_args(argc, argv, "11", &args.mutex, &args.timeout);

    w.th = GET_THREAD();
    list_add_tail(&cv->waitq, &w.node);
    rb_ensure(do_sleep, (VALUE)&args, delete_from_waitq, (VALUE)&w);

    return self;
}