Initial attempt at ConditionVariable implementation.
This commit is contained in:
1 parent
a1f881f59c
commit
d65979cc2e
2 files changed
+101
-4
No files matched your search
@@ -1,14 +1,16 @@
|
||||
require 'process_shared/semaphore'
|
||||
|
||||
module ProcessShared
|
||||
# TODO: implement this
|
||||
class ConditionVariable
|
||||
def initialize
|
||||
@sem = Semaphore.new
|
||||
@internal = Semaphore.new(1)
|
||||
@waiting = SharedMemory.new(:int)
|
||||
@waiting.write_int(0)
|
||||
@sem = Semaphore.new(0)
|
||||
end
|
||||
|
||||
def broadcast
|
||||
@sem.post
|
||||
waiting.times { @sem.post }
|
||||
end
|
||||
|
||||
def signal
|
||||
@@ -18,10 +20,38 @@ module ProcessShared
|
||||
def wait(mutex, timeout = nil)
|
||||
mutex.unlock
|
||||
begin
|
||||
@sem.wait
|
||||
inc_waiting
|
||||
if timeout
|
||||
begin
|
||||
@sem.try_wait(timeout)
|
||||
rescue Errno::EAGAIN, Errno::ETIMEDOUT
|
||||
# success!
|
||||
end
|
||||
else
|
||||
@sem.wait
|
||||
end
|
||||
dec_waiting
|
||||
ensure
|
||||
mutex.lock
|
||||
end
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def waiting
|
||||
@internal.synchronize do
|
||||
@waiting.read_int
|
||||
end
|
||||
end
|
||||
|
||||
def inc_waiting(val = 1)
|
||||
@internal.synchronize do
|
||||
@waiting.write_int(@waiting.read_int + val)
|
||||
end
|
||||
end
|
||||
|
||||
def dec_waiting
|
||||
inc_waiting(-1)
|
||||
end
|
||||
end
|
||||
end
|
||||
Reference in new issue
Block a user