Skip to content

Thread safety for URLSession #1210

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 2 commits into from
Sep 14, 2017
Merged
Changes from 1 commit
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
9 changes: 6 additions & 3 deletions Foundation/URLSession/URLSession.swift
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,7 @@ public let NSURLSessionTransferSizeUnknown: Int64 = -1
open class URLSession : NSObject {
fileprivate let _configuration: _Configuration
fileprivate let multiHandle: _MultiHandle
fileprivate let taskIdentifierLock = NSLock()
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

my only question is what is the preferred way, NSLock or a dispatch queue? I think we should be consistent. @phausler / @parkera do we have a preferred option?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I’ve switched to using the workQueue for consistency

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

also: the sessionDescription and delegate properties are also mutable and accessible from the outside. I suppose the should be locked too.

fileprivate var nextTaskIdentifier = 1
internal let workQueue: DispatchQueue
/// This queue is used to make public attributes on `URLSessionTask` instances thread safe.
Expand Down Expand Up @@ -406,9 +407,11 @@ extension URLSession._Request {

fileprivate extension URLSession {
func createNextTaskIdentifier() -> Int {
let i = nextTaskIdentifier
nextTaskIdentifier += 1
return i
return taskIdentifierLock.synchronized {
let i = nextTaskIdentifier
nextTaskIdentifier += 1
return i
}
}
}

Expand Down