Cotton code
43 lines · 1.5 KB · SwiftRaw
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<Value: Sendable>(        qos: DispatchQoS,        _ work: @escaping @Sendable () -> Value    ) -> Value {        let reply = Reply<Value>()        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<Value: Sendable>: @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! } }    }}