Avatar
@swift-5.3.3 @swift-5.7.3 import Foundation extension NSLock { func synchronized<T>(_ closure: () throws -> T) rethrows -> T { self.lock() defer { self.unlock() } return try closure() } } func test() throws { let task = Process() task.executableURL = URL(fileURLWithPath: "/usr/bin/which") task.arguments = [] let stdoutPipe = Pipe() let dataLock = NSLock() task.standardOutput = stdoutPipe var stdoutData = Data() stdoutPipe.fileHandleForReading.readabilityHandler = { fh in dataLock.synchronized { stdoutData.append(Data()) } } try task.run() task.waitUntilExit() stdoutPipe.fileHandleForReading.readabilityHandler = nil try dataLock.synchronized { if let d = try stdoutPipe.fileHandleForReading.readToEnd() { stdoutData.append(d) } } } for _ in 0..<100 { DispatchQueue.global().async { try! test() } } (edited)