Skip to content

Commit

Permalink
cherry-pick thread-safe event-shutdown authored by @Simon-Laux in #1969
Browse files Browse the repository at this point in the history
  • Loading branch information
r10s committed Dec 7, 2023
1 parent 671c819 commit 3972ded
Showing 1 changed file with 21 additions and 2 deletions.
23 changes: 21 additions & 2 deletions deltachat-ios/AppDelegate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -271,6 +271,7 @@ class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterD

func applicationWillTerminate(_: UIApplication) {
logger.info("⬅️ applicationWillTerminate")
uninstallEventHandler()
dcAccounts.closeDatabase()
if let reachability = reachability {
reachability.stopNotifier()
Expand Down Expand Up @@ -597,19 +598,37 @@ class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterD
}
}

func installEventHandler() {
private var shouldShutdownEventLoop = false
private var eventHandlerActive = false
private var eventShutdownSemaphore = DispatchSemaphore(value: 0)

private func installEventHandler() {
if eventHandlerActive {
return
}
eventHandlerActive = true
DispatchQueue.global(qos: .background).async { [weak self] in
guard let self = self else { return }
let eventHandler = DcEventHandler(dcAccounts: self.dcAccounts)
let eventEmitter = self.dcAccounts.getEventEmitter()
while true {
logger.info("➡️ event emitter started")
while !shouldShutdownEventLoop {
guard let event = eventEmitter.getNextEvent() else { break }
eventHandler.handleEvent(event: event)
}
logger.info("⬅️ event emitter finished")
eventShutdownSemaphore.signal()
eventHandlerActive = false
}
}

private func uninstallEventHandler() {
shouldShutdownEventLoop = true
dcAccounts.stopIo() // stopIo will generate atleast one event to the event handler can shut down
eventShutdownSemaphore.wait()
shouldShutdownEventLoop = false
}

// Values calculated for debug log view
private func increaseDebugCounter(_ name: String) {
let nowDate = Date()
Expand Down

0 comments on commit 3972ded

Please sign in to comment.