Skip to content

Commit 7bcff33

Browse files
committed
Add Thread.delay
1 parent 95e4ad0 commit 7bcff33

File tree

2 files changed

+16
-2
lines changed

2 files changed

+16
-2
lines changed

src/crystal/system/thread.cr

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -179,6 +179,18 @@ class Thread
179179
Crystal::System::Thread.sleep(time)
180180
end
181181

182+
# Delays execution for a brief moment.
183+
@[NoInline]
184+
def self.delay(backoff : Int32) : Int32
185+
if backoff < 7
186+
backoff.times { Intrinsics.pause }
187+
backoff &+ 1
188+
else
189+
Thread.yield
190+
0
191+
end
192+
end
193+
182194
# Returns the Thread object associated to the running system thread.
183195
def self.current : Thread
184196
Crystal::System::Thread.current_thread

src/fiber/execution_context/multi_threaded/scheduler.cr

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -66,15 +66,17 @@ module Fiber::ExecutionContext
6666
# fiber but thread B didn't saved its context yet); we must wait until
6767
# the context switch assembly saved all registers on the stack and set
6868
# the fiber as resumable.
69+
attempts = 0
70+
6971
until fiber.resumable?
7072
if fiber.dead?
7173
raise "BUG: tried to resume dead fiber #{fiber} (#{inspect})"
7274
end
7375

7476
# OPTIMIZE: if the thread saving the fiber context has been preempted,
7577
# this will block the current thread from progressing... shall we
76-
# abort and reenqueue the fiber after MAX iterations?
77-
Intrinsics.pause
78+
# abort and reenqueue the fiber after MAX attempts?
79+
attempts = Thread.delay(attempts)
7880
end
7981

8082
swapcontext(fiber)

0 commit comments

Comments
 (0)