Skip to content

Commit 7d699e8

Browse files
committed
Optimized Event
1 parent 3c80ad3 commit 7d699e8

File tree

1 file changed

+29
-14
lines changed

1 file changed

+29
-14
lines changed

lib/concurrent/atomic/event.rb

Lines changed: 29 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -28,41 +28,52 @@ def initialize
2828
#
2929
# @return [Boolean] indicating whether or not the `Event` has been set
3030
def set?
31-
@mutex.synchronize do
32-
@set
33-
end
31+
@mutex.lock
32+
result = @set
33+
@mutex.unlock
34+
35+
result
3436
end
3537

3638
# Trigger the event, setting the state to `set` and releasing all threads
3739
# waiting on the event. Has no effect if the `Event` has already been set.
3840
#
3941
# @return [Boolean] should always return `true`
4042
def set
41-
@mutex.synchronize do
42-
return true if @set
43+
@mutex.lock
44+
unless @set
4345
@set = true
4446
@condition.broadcast
4547
end
48+
@mutex.unlock
4649

4750
true
4851
end
4952

5053
def try?
51-
@mutex.synchronize do
52-
return false if @set
54+
@mutex.lock
55+
56+
if @set
57+
result = false
58+
else
5359
@set = true
5460
@condition.broadcast
61+
result = true
5562
end
63+
64+
@mutex.unlock
65+
66+
result
5667
end
5768

5869
# Reset a previously set event back to the `unset` state.
5970
# Has no effect if the `Event` has not yet been set.
6071
#
6172
# @return [Boolean] should always return `true`
6273
def reset
63-
@mutex.synchronize do
64-
@set = false
65-
end
74+
@mutex.lock
75+
@set = false
76+
@mutex.unlock
6677

6778
true
6879
end
@@ -73,16 +84,20 @@ def reset
7384
#
7485
# @return [Boolean] true if the `Event` was set before timeout else false
7586
def wait(timeout = nil)
76-
@mutex.synchronize do
77-
return true if @set
87+
@mutex.lock
7888

89+
unless @set
7990
remaining = Condition::Result.new(timeout)
8091
while !@set && remaining.can_wait?
8192
remaining = @condition.wait(@mutex, remaining.remaining_time)
8293
end
83-
84-
@set
8594
end
95+
96+
result = @set
97+
98+
@mutex.unlock
99+
100+
result
86101
end
87102
end
88103
end

0 commit comments

Comments
 (0)