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:

require 'thread'

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.



1132
1133
1134
1135
1136
1137
# File 'thread_sync.c', line 1132

static VALUE
rb_condvar_initialize(VALUE self)
{
    RSTRUCT_SET(self, CONDVAR_WAITERS, ary_buf_new());
    return self;
}

Instance Method Details

#broadcastObject

Wakes up all threads waiting for this lock.



1205
1206
1207
1208
1209
1210
# File 'thread_sync.c', line 1205

static VALUE
rb_condvar_broadcast(VALUE self)
{
    wakeup_all_threads(GET_CONDVAR_WAITERS(self));
    return self;
}

#marshal_dumpObject

:nodoc:



1213
1214
1215
1216
1217
1218
# File 'thread_sync.c', line 1213

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

#signalObject

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



1192
1193
1194
1195
1196
1197
# File 'thread_sync.c', line 1192

static VALUE
rb_condvar_signal(VALUE self)
{
    wakeup_first_thread(GET_CONDVAR_WAITERS(self));
    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.



1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
# File 'thread_sync.c', line 1169

static VALUE
rb_condvar_wait(int argc, VALUE *argv, VALUE self)
{
    VALUE waiters = GET_CONDVAR_WAITERS(self);
    VALUE mutex, timeout;
    struct sleep_call args;

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

    args.mutex   = mutex;
    args.timeout = timeout;
    rb_ary_push(waiters, rb_thread_current());
    rb_ensure(do_sleep, (VALUE)&args, delete_current_thread, waiters);

    return self;
}