Skip to content

OperationQueue.main dangling pointer fix #1094

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 4 commits into from
Jul 6, 2017
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
18 changes: 8 additions & 10 deletions Foundation/Operation.swift
Original file line number Diff line number Diff line change
Expand Up @@ -563,29 +563,27 @@ open class OperationQueue: NSObject {

open class var current: OperationQueue? {
#if DEPLOYMENT_ENABLE_LIBDISPATCH
let specific = DispatchQueue.getSpecific(key: OperationQueue.OperationQueueKey)
if specific == nil {
guard let specific = DispatchQueue.getSpecific(key: OperationQueue.OperationQueueKey) else {
if pthread_main_np() == 1 {
return OperationQueue.main
} else {
return nil
}
} else {
return specific!.takeUnretainedValue()
}

return specific.takeUnretainedValue()
#else
return nil
#endif
}

#if DEPLOYMENT_ENABLE_LIBDISPATCH
private static let _main = OperationQueue(_queue: .main, maxConcurrentOperations: 1)
#endif

open class var main: OperationQueue {
#if DEPLOYMENT_ENABLE_LIBDISPATCH
let specific = DispatchQueue.main.getSpecific(key: OperationQueue.OperationQueueKey)
if specific == nil {
return OperationQueue(_queue: DispatchQueue.main, maxConcurrentOperations: 1)
} else {
return specific!.takeUnretainedValue()
}
return _main
#else
fatalError("NSOperationQueue requires libdispatch")
#endif
Expand Down
11 changes: 11 additions & 0 deletions TestFoundation/TestNSOperationQueue.swift
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ class TestNSOperationQueue : XCTestCase {
("test_OperationCount", test_OperationCount),
("test_AsyncOperation", test_AsyncOperation),
("test_isExecutingWorks", test_isExecutingWorks),
("test_MainQueueGetter", test_MainQueueGetter),
]
}

Expand Down Expand Up @@ -103,6 +104,16 @@ class TestNSOperationQueue : XCTestCase {
XCTAssertFalse(operation.isExecuting)
XCTAssertTrue(operation.isFinished)
}

func test_MainQueueGetter() {
XCTAssertTrue(OperationQueue.main === OperationQueue.main)

/*
This call is only to check if OperationQueue.main returns a living instance.
There used to be a bug where subsequent OperationQueue.main call would return a "dangling pointer".
*/
XCTAssertFalse(OperationQueue.main.isSuspended)
}
}

class AsyncOperation: Operation {
Expand Down