fix: app would sometimes crash at launch (closes #607)
This commit is contained in:
1 parent
473e08fd01
commit
7288013691
1 file changed
+8
@@ -12,6 +12,8 @@ class BackgroundWork {
|
|||||||
|
|
||||||
// we cap concurrent tasks to .processorCount to avoid thread explosion on the .global queue
|
// we cap concurrent tasks to .processorCount to avoid thread explosion on the .global queue
|
||||||
static let globalSemaphore = DispatchSemaphore(value: ProcessInfo.processInfo.processorCount)
|
static let globalSemaphore = DispatchSemaphore(value: ProcessInfo.processInfo.processorCount)
|
||||||
|
// Thread.start() is async; we use a semaphore to ensure threads are actually ready before we continue the launch sequence
|
||||||
|
static let threadStartSemaphore = DispatchSemaphore(value: 0)
|
||||||
|
|
||||||
// swift static variables are lazy; we artificially force the threads to init
|
// swift static variables are lazy; we artificially force the threads to init
|
||||||
static func start() {
|
static func start() {
|
||||||
@@ -50,11 +52,16 @@ extension DispatchQueue {
|
|||||||
class BackgroundThreadWithRunLoop {
|
class BackgroundThreadWithRunLoop {
|
||||||
var thread: Thread?
|
var thread: Thread?
|
||||||
var runLoop: CFRunLoop?
|
var runLoop: CFRunLoop?
|
||||||
|
var hasSentSemaphoreSignal = false
|
||||||
|
|
||||||
init(_ name: String, _ qos: DispatchQoS) {
|
init(_ name: String, _ qos: DispatchQoS) {
|
||||||
thread = Thread {
|
thread = Thread {
|
||||||
self.runLoop = CFRunLoopGetCurrent()
|
self.runLoop = CFRunLoopGetCurrent()
|
||||||
while !self.thread!.isCancelled {
|
while !self.thread!.isCancelled {
|
||||||
|
if !self.hasSentSemaphoreSignal {
|
||||||
|
BackgroundWork.threadStartSemaphore.signal()
|
||||||
|
self.hasSentSemaphoreSignal = true
|
||||||
|
}
|
||||||
CFRunLoopRun()
|
CFRunLoopRun()
|
||||||
// avoid tight loop while waiting for the first runloop source to be added
|
// avoid tight loop while waiting for the first runloop source to be added
|
||||||
Thread.sleep(forTimeInterval: 0.1)
|
Thread.sleep(forTimeInterval: 0.1)
|
||||||
@@ -63,5 +70,6 @@ class BackgroundThreadWithRunLoop {
|
|||||||
thread!.name = name
|
thread!.name = name
|
||||||
thread!.qualityOfService = qos.toQualityOfService()
|
thread!.qualityOfService = qos.toQualityOfService()
|
||||||
thread!.start()
|
thread!.start()
|
||||||
|
BackgroundWork.threadStartSemaphore.wait()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Reference in new issue
Block a user