@@ -2,8 +2,6 @@ module Concurrent
2
2
3
3
class CyclicBarrier
4
4
5
- BrokenError = Class . new ( StandardError )
6
-
7
5
Generation = Struct . new ( :status )
8
6
private_constant :Generation
9
7
@@ -42,45 +40,28 @@ def wait(timeout = nil)
42
40
43
41
return false unless @generation . status == :waiting
44
42
45
- generation = @generation
46
-
47
43
@number_waiting += 1
48
44
49
45
if @number_waiting == @parties
50
46
@action . call if @action
51
- generation . status = :fulfilled
52
- @generation = Generation . new ( :waiting )
53
- @condition . broadcast
54
- @number_waiting = 0
47
+ set_status_and_restore ( :fulfilled )
55
48
true
56
49
else
57
- remaining = Condition ::Result . new ( timeout )
58
- while generation . status == :waiting && remaining . can_wait?
59
- remaining = @condition . wait ( @mutex , remaining . remaining_time )
60
- end
61
-
62
- if remaining . woken_up?
63
- return generation . status == :fulfilled
64
- else
65
- generation . status = :broken
66
- @condition . broadcast
67
- return false
68
- end
50
+ wait_for_wake_up ( @generation , timeout )
69
51
end
70
52
end
71
53
end
72
54
55
+
56
+
73
57
# resets the barrier to its initial state
74
58
# If there is at least one waiting thread, it will be woken up, the `wait` method will return false and the barrier will be broken
75
59
# If the barrier is broken, this method restores it to the original state
76
60
#
77
61
# @return [nil]
78
62
def reset
79
63
@mutex . synchronize do
80
- @generation . status = :reset
81
- @condition . broadcast
82
- @generation = Generation . new ( :waiting )
83
- @number_waiting = 0
64
+ set_status_and_restore ( :reset )
84
65
end
85
66
end
86
67
@@ -94,5 +75,32 @@ def broken?
94
75
@mutex . synchronize { @generation . status != :waiting }
95
76
end
96
77
78
+ private
79
+
80
+ def set_status_and_restore ( new_status )
81
+ @generation . status = new_status
82
+ @condition . broadcast
83
+ @generation = Generation . new ( :waiting )
84
+ @number_waiting = 0
85
+ end
86
+
87
+ def wait_for_wake_up ( generation , timeout )
88
+ if wait_while_waiting ( generation , timeout )
89
+ generation . status == :fulfilled
90
+ else
91
+ generation . status = :broken
92
+ @condition . broadcast
93
+ false
94
+ end
95
+ end
96
+
97
+ def wait_while_waiting ( generation , timeout )
98
+ remaining = Condition ::Result . new ( timeout )
99
+ while generation . status == :waiting && remaining . can_wait?
100
+ remaining = @condition . wait ( @mutex , remaining . remaining_time )
101
+ end
102
+ remaining . woken_up?
103
+ end
104
+
97
105
end
98
106
end
0 commit comments