Skip to content

NSCondition fixes: Ensure correct use of lock()/action/unlock() sequence #1613

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jun 20, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 13 additions & 2 deletions Foundation/NSData.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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!
}
Expand Down
2 changes: 1 addition & 1 deletion Foundation/Process.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 2 additions & 2 deletions TestFoundation/TestNSLock.swift
Original file line number Diff line number Diff line change
Expand Up @@ -68,15 +68,15 @@ class TestNSLock: XCTestCase {

for t in 0..<threadCount {
let thread = Thread() {
condition.lock()
arrayLock.lock()
threadsStarted[t] = true
arrayLock.unlock()

condition.lock()
condition.wait()
condition.unlock()
for _ in 1...50 {
let r = (endSeconds * drand48()) / 50
let r = Double.random(in: 0...0.02)
Thread.sleep(forTimeInterval: r)
if lock.lock(before: endTime) {
lock.unlock()
Expand Down
2 changes: 1 addition & 1 deletion TestFoundation/TestThread.swift
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ class TestThread : XCTestCase {
}
thread.start()

let ok = condition.wait(until: Date(timeIntervalSinceNow: 10))
let ok = condition.wait(until: Date(timeIntervalSinceNow: 2))
condition.unlock()
XCTAssertTrue(ok, "NSCondition wait timed out")
}
Expand Down