Skip to content

Commit

Permalink
Ensure timer operations are executed on the main thread
Browse files Browse the repository at this point in the history
  • Loading branch information
xtyxtyx committed Jan 17, 2025
1 parent bde7d54 commit 7539e22
Showing 1 changed file with 11 additions and 2 deletions.
13 changes: 11 additions & 2 deletions Sources/Shaft/Backend/SDLBackend.swift
Original file line number Diff line number Diff line change
Expand Up @@ -504,13 +504,15 @@ private class SDLTimerManager {
private var callbackByTimerID: [SDL_TimerID: VoidCallback] = [:]

public func createTimer(_ delay: Duration, _ callback: @escaping VoidCallback) -> SDLTimer {
assert(backend.isMainThread)
let timerID = SDL_AddTimer(Uint32(delay.inMilliseconds), sdlTimerCallback, nil)
let timer = SDLTimer(timerID)
callbackByTimerID[timer.timerID] = callback
return timer
}

public func cancelTimer(_ timerID: SDL_TimerID) {
assert(backend.isMainThread)
SDL_RemoveTimer(timerID)
callbackByTimerID.removeValue(forKey: timerID)
}
Expand All @@ -519,10 +521,17 @@ private class SDLTimerManager {
return callbackByTimerID[timerID] != nil
}

public func fireTimer(_ timerID: SDL_TimerID) {
fileprivate func fireTimer(_ timerID: SDL_TimerID) {
backend.runOnMainThread {
self.fireTimerInner(timerID)
}
}

private func fireTimerInner(_ timerID: SDL_TimerID) {
assert(backend.isMainThread)
if let callback = callbackByTimerID[timerID] {
callbackByTimerID.removeValue(forKey: timerID)
SDLBackend.shared.runOnMainThread(callback)
callback()
}
}
}
Expand Down

0 comments on commit 7539e22

Please sign in to comment.