import Foundation /// GCD schedules calls and their close barriers; this thread lends each /// native operation the stack Rust's debug definition decoder requires. /// Waiting keeps the enclosing queue block alive until native work returns, /// so its close barrier cannot free a handle still running on this thread. enum CoreNativeThread { static func run( qos: DispatchQoS, _ work: @escaping @Sendable () -> Value ) -> Value { let reply = Reply() let thread = Thread { autoreleasepool { reply.store(work()) } reply.finished.signal() } thread.name = "com.cottondb.core.native" thread.stackSize = 8 * 1024 * 1024 thread.qualityOfService = quality(of: qos) thread.start() reply.finished.wait() return reply.take() } private static func quality(of qos: DispatchQoS) -> QualityOfService { switch qos.qosClass { case .userInteractive: .userInteractive case .userInitiated: .userInitiated case .utility: .utility case .background: .background default: .default } } private final class Reply: @unchecked Sendable { let finished = DispatchSemaphore(value: 0) private let lock = NSLock() private var value: Value? func store(_ answer: Value) { lock.withLock { value = answer } } func take() -> Value { lock.withLock { value! } } } }