Class: ConditionVariable
- Inherits:
-
Object
- Object
- ConditionVariable
- Defined in:
- thread.c,
thread.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
-
#broadcast ⇒ Object
Wakes up all threads waiting for this lock.
-
#initialize ⇒ Object
constructor
Creates a new condition variable instance.
-
#signal ⇒ Object
Wakes up the first thread in line waiting for this lock.
-
#wait(mutex, timeout = nil) ⇒ Object
Releases the lock held in
mutex
and waits; reacquires the lock on wakeup.
Constructor Details
#initialize ⇒ Object
Creates a new condition variable instance.
87 88 89 90 91 92 |
# File 'thread.c', line 87
static VALUE
rb_condvar_initialize(VALUE self)
{
RSTRUCT_SET(self, CONDVAR_WAITERS, ary_buf_new());
return self;
}
|
Instance Method Details
#broadcast ⇒ Object
Wakes up all threads waiting for this lock.
160 161 162 163 164 165 |
# File 'thread.c', line 160
static VALUE
rb_condvar_broadcast(VALUE self)
{
wakeup_all_threads(GET_CONDVAR_WAITERS(self));
return self;
}
|
#signal ⇒ Object
Wakes up the first thread in line waiting for this lock.
147 148 149 150 151 152 |
# File 'thread.c', line 147
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.
124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 |
# File 'thread.c', line 124
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;
}
|