@@ -11,8 +11,7 @@ def initialize
1111 @root_fiber = Fiber . current
1212 @dns_cache = { }
1313
14- @alive_fibers = Hash . new { |h , k | h [ k ] = { } }
15- @fibers_mutex = Mutex . new
14+ @fiber_timeouts = Hash . new { |h , k | h [ k ] = { } }
1615
1716 start_timeout_worker
1817 end
@@ -75,23 +74,18 @@ def kernel_sleep(duration = nil)
7574
7675 def timeout_after ( duration , exception_class = Timeout ::Error , *exception_arguments , &block )
7776 fiber = Fiber . current
78- timeout_deadline = Process . clock_gettime ( Process ::CLOCK_MONOTONIC ) + duration
79-
80- @fibers_mutex . synchronize do
81- @alive_fibers [ fiber . __get_id ] [ timeout_deadline ] = {
82- fiber : fiber ,
83- timeout_deadline : timeout_deadline ,
84- exception_class : exception_class ,
85- exception_arguments : exception_arguments
86- }
87- end
77+ timeout = Process . clock_gettime ( Process ::CLOCK_MONOTONIC ) + duration
78+
79+ @fiber_timeouts [ fiber ] [ timeout ] = {
80+ exception_class : exception_class ,
81+ exception_arguments : exception_arguments
82+ }
8883
8984 begin
9085 block . call
9186 ensure
92- @fibers_mutex . synchronize do
93- @alive_fibers [ fiber . __get_id ] . delete ( timeout_deadline )
94- end
87+ @fiber_timeouts [ fiber ] . delete ( timeout )
88+ @fiber_timeouts . delete ( fiber ) if @fiber_timeouts [ fiber ] . empty?
9589 end
9690 end
9791
@@ -164,38 +158,19 @@ def close
164158 private
165159
166160 def start_timeout_worker
167- return unless ::Iodine . running?
168-
169161 ::Iodine . run_every ( Rage ::FiberScheduler ::TIMEOUT_WORKER_INTERVAL ) do
170162 check_timeouts
171163 end
172164 end
173165
174166 def check_timeouts
175- @fibers_mutex . synchronize do
176- @alive_fibers . delete_if do |fiber_id , fiber_timeouts |
177- fiber_timeouts . delete_if do |timeout_key , fiber_context |
178- current_time = Process . clock_gettime ( Process ::CLOCK_MONOTONIC )
179-
180- next false if current_time < fiber_context [ :timeout_deadline ]
181-
182- fiber = fiber_context [ :fiber ]
183- unblock ( nil , fiber )
184-
185- if fiber . alive?
186- fiber . raise ( fiber_context [ :exception_class ] , *fiber_context [ :exception_arguments ] )
187-
188- ::Iodine . run_after ( FIBER_KILL_DELAY ) do
189- fiber . kill if fiber . alive?
190- end
191- else
192- fiber_timeouts . delete ( timeout_key )
193- end
167+ @fiber_timeouts . each_pair do |fiber , timeouts |
168+ timeouts . delete_if do |timeout , context |
169+ next false if Process . clock_gettime ( Process ::CLOCK_MONOTONIC ) < timeout
194170
195- true
196- end
171+ fiber . raise ( context [ :exception_class ] , *context [ :exception_arguments ] ) if fiber . alive?
197172
198- fiber_timeouts . length == 0
173+ true
199174 end
200175 end
201176 end
0 commit comments