Skip to content

Commit 4ecfe50

Browse files
committed
Fix thread safety issues by using a serial DispatchQueue for C library calls
1 parent 402f20a commit 4ecfe50

1 file changed

Lines changed: 11 additions & 5 deletions

File tree

Sources/SQLClientSwift/SQLClient.swift

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -131,6 +131,8 @@ public actor SQLClient {
131131
public static let shared = SQLClient()
132132
public init() {}
133133

134+
private let queue = DispatchQueue(label: "com.sqlclient.serial")
135+
134136
public var maxTextSize: Int = 4096
135137
private var login: OpaquePointer?
136138
private var connection: OpaquePointer?
@@ -201,7 +203,7 @@ public actor SQLClient {
201203
/// Not called automatically — integrate tests and CI skip it safely this way.
202204
public func checkReachability(server: String, port: UInt16 = 1433) async throws {
203205
try await withCheckedThrowingContinuation { (cont: CheckedContinuation<Void, Error>) in
204-
Thread.detachNewThread {
206+
queue.async {
205207
var readStream: Unmanaged<CFReadStream>?
206208
var writeStream: Unmanaged<CFWriteStream>?
207209
CFStreamCreatePairWithSocketToHost(
@@ -453,16 +455,20 @@ public actor SQLClient {
453455

454456
private func runBlocking<T: Sendable>(_ body: @Sendable @escaping () throws -> T) async throws -> T {
455457
try await withCheckedThrowingContinuation { continuation in
456-
Thread.detachNewThread {
457-
do { continuation.resume(returning: try body()) }
458-
catch { continuation.resume(throwing: error) }
458+
queue.async {
459+
do {
460+
let result = try body()
461+
continuation.resume(returning: result)
462+
} catch {
463+
continuation.resume(throwing: error)
464+
}
459465
}
460466
}
461467
}
462468

463469
private func runBlockingVoid(_ body: @Sendable @escaping () -> Void) async {
464470
await withCheckedContinuation { continuation in
465-
Thread.detachNewThread {
471+
queue.async {
466472
body()
467473
continuation.resume()
468474
}

0 commit comments

Comments
 (0)