From ce7698d417eb7bece3dead2d66adca6373565744 Mon Sep 17 00:00:00 2001 From: Simon Evans Date: Wed, 20 Jun 2018 14:09:50 +0100 Subject: [PATCH] NSCondition fixes: Ensure correct use of lock()/action/unlock() sequence --- Foundation/NSData.swift | 15 +++++++++++++-- Foundation/Process.swift | 2 +- TestFoundation/TestNSLock.swift | 4 ++-- TestFoundation/TestThread.swift | 2 +- 4 files changed, 17 insertions(+), 6 deletions(-) diff --git a/Foundation/NSData.swift b/Foundation/NSData.swift index d4eea5ac7d..993f5e0156 100644 --- a/Foundation/NSData.swift +++ b/Foundation/NSData.swift @@ -210,16 +210,27 @@ open class NSData : NSObject, NSCopying, NSMutableCopying, NSSecureCoding { } else { let session = URLSession(configuration: URLSessionConfiguration.default) let cond = NSCondition() + cond.lock() + var resError: Error? var resData: Data? + var taskFinished = false let task = session.dataTask(with: url, completionHandler: { data, response, error in + cond.lock() resData = data urlResponse = response resError = error - cond.broadcast() + taskFinished = true + cond.signal() + cond.unlock() }) + task.resume() - cond.wait() + while taskFinished == false { + cond.wait() + } + cond.unlock() + guard let data = resData else { throw resError! } diff --git a/Foundation/Process.swift b/Foundation/Process.swift index 47ba49b950..7139a5587c 100644 --- a/Foundation/Process.swift +++ b/Foundation/Process.swift @@ -242,8 +242,8 @@ open class Process: NSObject { self.processLaunchedCondition.lock() defer { - self.processLaunchedCondition.unlock() self.processLaunchedCondition.broadcast() + self.processLaunchedCondition.unlock() } // Dispatch the manager thread if it isn't already running diff --git a/TestFoundation/TestNSLock.swift b/TestFoundation/TestNSLock.swift index a86365815b..2bca129de1 100644 --- a/TestFoundation/TestNSLock.swift +++ b/TestFoundation/TestNSLock.swift @@ -68,15 +68,15 @@ class TestNSLock: XCTestCase { for t in 0..