Skip to content
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
59 changes: 55 additions & 4 deletions Concurrency.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@
41B94842210A4744007E59C8 /* Task.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Task.swift; sourceTree = "<group>"; };
41B94848210A4756007E59C8 /* ConcurrentSequenceExecutorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ConcurrentSequenceExecutorTests.swift; sourceTree = "<group>"; };
"Concurrency::Concurrency::Product" /* Concurrency.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; path = Concurrency.framework; sourceTree = BUILT_PRODUCTS_DIR; };
"Concurrency::ConcurrencyTests::Product" /* ConcurrencyTests.xctest */ = {isa = PBXFileReference; lastKnownFileType = file; path = ConcurrencyTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };
"Concurrency::ConcurrencyTests::Product" /* ConcurrencyTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; path = ConcurrencyTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };
OBJ_10 /* AtomicInt.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AtomicInt.swift; sourceTree = "<group>"; };
OBJ_11 /* AtomicReference.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AtomicReference.swift; sourceTree = "<group>"; };
OBJ_12 /* CountDownLatch.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CountDownLatch.swift; sourceTree = "<group>"; };
Expand Down Expand Up @@ -193,7 +193,7 @@
OBJ_1 /* Project object */ = {
isa = PBXProject;
attributes = {
LastUpgradeCheck = 9999;
LastUpgradeCheck = 1000;
};
buildConfigurationList = OBJ_2 /* Build configuration list for PBXProject "Concurrency" */;
compatibilityVersion = "Xcode 3.2";
Expand Down Expand Up @@ -302,12 +302,38 @@
isa = XCBuildConfiguration;
buildSettings = {
CLANG_ENABLE_OBJC_ARC = YES;
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_COMMA = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
CLANG_WARN_STRICT_PROTOTYPES = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
COMBINE_HIDPI_IMAGES = YES;
COPY_PHASE_STRIP = NO;
DEBUG_INFORMATION_FORMAT = dwarf;
DYLIB_INSTALL_NAME_BASE = "@rpath";
ENABLE_NS_ASSERTIONS = YES;
ENABLE_STRICT_OBJC_MSGSEND = YES;
ENABLE_TESTABILITY = YES;
GCC_NO_COMMON_BLOCKS = YES;
GCC_OPTIMIZATION_LEVEL = 0;
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES;
GCC_WARN_UNDECLARED_SELECTOR = YES;
GCC_WARN_UNINITIALIZED_AUTOS = YES;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 8.0;
MACOSX_DEPLOYMENT_TARGET = 10.10;
ONLY_ACTIVE_ARCH = YES;
Expand All @@ -325,11 +351,36 @@
isa = XCBuildConfiguration;
buildSettings = {
CLANG_ENABLE_OBJC_ARC = YES;
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_COMMA = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
CLANG_WARN_STRICT_PROTOTYPES = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
COMBINE_HIDPI_IMAGES = YES;
COPY_PHASE_STRIP = YES;
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
DYLIB_INSTALL_NAME_BASE = "@rpath";
ENABLE_STRICT_OBJC_MSGSEND = YES;
GCC_NO_COMMON_BLOCKS = YES;
GCC_OPTIMIZATION_LEVEL = s;
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES;
GCC_WARN_UNDECLARED_SELECTOR = YES;
GCC_WARN_UNINITIALIZED_AUTOS = YES;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 8.0;
MACOSX_DEPLOYMENT_TARGET = 10.10;
OTHER_SWIFT_FLAGS = "-DXcode";
Expand All @@ -345,7 +396,7 @@
OBJ_45 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
EMBEDDED_CONTENT_CONTAINS_SWIFT = YES;
ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES;
FRAMEWORK_SEARCH_PATHS = (
"$(inherited)",
"$(PLATFORM_DIR)/Developer/Library/Frameworks",
Expand All @@ -364,7 +415,7 @@
OBJ_46 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
EMBEDDED_CONTENT_CONTAINS_SWIFT = YES;
ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES;
FRAMEWORK_SEARCH_PATHS = (
"$(inherited)",
"$(PLATFORM_DIR)/Developer/Library/Frameworks",
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "9999"
LastUpgradeVersion = "1000"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
Expand Down Expand Up @@ -28,16 +28,6 @@
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES">
<Testables>
<TestableReference
skipped = "NO">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "Concurrency::ConcurrencyTests"
BuildableName = "ConcurrencyTests.xctest"
BlueprintName = "ConcurrencyTests"
ReferencedContainer = "container:Concurrency.xcodeproj">
</BuildableReference>
</TestableReference>
</Testables>
<AdditionalOptions>
</AdditionalOptions>
Expand Down Expand Up @@ -70,6 +60,15 @@
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
debugDocumentVersioning = "YES">
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "Concurrency::Concurrency"
BuildableName = "Concurrency.framework"
BlueprintName = "Concurrency"
ReferencedContainer = "container:Concurrency.xcodeproj">
</BuildableReference>
</MacroExpansion>
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "1000"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES">
</BuildAction>
<TestAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES">
<Testables>
<TestableReference
skipped = "NO">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "Concurrency::ConcurrencyTests"
BuildableName = "ConcurrencyTests.xctest"
BlueprintName = "ConcurrencyTests"
ReferencedContainer = "container:Concurrency.xcodeproj">
</BuildableReference>
</TestableReference>
</Testables>
<AdditionalOptions>
</AdditionalOptions>
</TestAction>
<LaunchAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
debugServiceExtension = "internal"
allowLocationSimulation = "YES">
<AdditionalOptions>
</AdditionalOptions>
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
debugDocumentVersioning = "YES">
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>
21 changes: 19 additions & 2 deletions Sources/Concurrency/Executor/ConcurrentSequenceExecutor.swift
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,15 @@ public class ConcurrentSequenceExecutor: SequenceExecutor {
/// - parameter name: The name of the executor.
/// - parameter qos: The quality of service of this executor. This
/// defaults to `userInitiated`.
public init(name: String, qos: DispatchQoS = .userInitiated) {
/// - parameter shouldTackTaskId: `true` if task IDs should be tracked
/// as tasks are executed. `false` otherwise. By tracking the task IDs,
/// if waiting on the completion of a task sequence times out, the
/// reported error contains the ID of the task that was being executed
/// when the timeout occurred. The tracking does incur a minor
/// performance cost. This value defaults to `false`.
public init(name: String, qos: DispatchQoS = .userInitiated, shouldTackTaskId: Bool = false) {
taskQueue = DispatchQueue(label: "Executor.taskQueue-\(name)", qos: qos, attributes: .concurrent)
self.shouldTackTaskId = shouldTackTaskId
}

/// Execute a sequence of tasks concurrently from the given initial task.
Expand All @@ -51,13 +58,18 @@ public class ConcurrentSequenceExecutor: SequenceExecutor {
// MARK: - Private

private let taskQueue: DispatchQueue
private let shouldTackTaskId: Bool

private func execute<SequenceResultType>(_ task: Task, with sequenceHandle: SynchronizedSequenceExecutionHandle<SequenceResultType>, _ execution: @escaping (Task, Any) -> SequenceExecution<SequenceResultType>) {
taskQueue.async {
guard !sequenceHandle.isCancelled else {
return
}

if self.shouldTackTaskId {
sequenceHandle.willBeginExecuting(taskId: task.id)
}

let result = task.typeErasedExecute()
let nextExecution = execution(task, result)
switch nextExecution {
Expand All @@ -74,6 +86,7 @@ private class SynchronizedSequenceExecutionHandle<SequenceResultType>: SequenceE

private let latch = CountDownLatch(count: 1)
private let didCancel = AtomicBool(initialValue: false)
private let currentTaskId = AtomicInt(initialValue: nonTrackingDefaultTaskId)

// Use a lock to ensure result is properly accessed, since the read
// `await` method may be invoked on a different thread than the write
Expand All @@ -85,10 +98,14 @@ private class SynchronizedSequenceExecutionHandle<SequenceResultType>: SequenceE
return didCancel.value
}

fileprivate func willBeginExecuting(taskId: Int) {
currentTaskId.value = taskId
}

fileprivate override func await(withTimeout timeout: TimeInterval?) throws -> SequenceResultType {
let didComplete = latch.await(timeout: timeout)
if !didComplete {
throw SequenceExecutionError.awaitTimeout
throw SequenceExecutionError.awaitTimeout(currentTaskId.value)
}

resultLock.lock()
Expand Down
8 changes: 6 additions & 2 deletions Sources/Concurrency/Executor/SequenceExecutor.swift
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,12 @@ import Foundation

/// Errors that can occur during a sequence execution.
public enum SequenceExecutionError: Error {
/// The waiting on sequence completion timed out.
case awaitTimeout
/// The waiting on sequence completion timed out. The `Int` value
/// indicates the ID of the task that was being executed when the
/// timeout occurred. If the value is `nonTrackingDefaultTaskId`,
/// then the executor was not configured to track task IDs during
/// initialization.
case awaitTimeout(Int)
}

/// The handle of the execution of a sequence of tasks, that allows control
Expand Down
15 changes: 14 additions & 1 deletion Sources/Concurrency/Executor/Task.swift
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,17 @@

import Foundation

public let nonTrackingDefaultTaskId = Int.min

/// An individual unit of work that can be executed in a concurrent
/// environment by an executor.
// Task cannot be generic since it needs to be referenced by the executor
// class which cannot provide type information for specific tasks.
public protocol Task {

/// A unique ID number identifying the task.
var id: Int { get }

/// Execute this task without any type information.
///
/// - note: This method should only be used by internal executor
Expand All @@ -41,8 +46,16 @@ public protocol Task {
// wildcard generics.
open class AbstractTask<ResultType>: Task {

/// A unique ID number identifying the task.
public let id: Int

/// Initializer.
public init() {}
///
/// - parameter id: A unique ID number identifying the task. This value
/// defaults to `nonTrackingDefaultTaskId`.
public init(id: Int = nonTrackingDefaultTaskId) {
self.id = id
}

/// Execute this task without any type information.
///
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -122,14 +122,14 @@ class ConcurrentSequenceExecutorTests: XCTestCase {
}

func test_executeSequence_withNonTerminatingSequence_withTimeout_verifyAwaitTimeout() {
let executor = ConcurrentSequenceExecutor(name: "test_executeSequence_withNonTerminatingSequence_withTimeout_verifyAwaitTimeout")
let executor = ConcurrentSequenceExecutor(name: "test_executeSequence_withNonTerminatingSequence_withTimeout_verifyAwaitTimeout", shouldTackTaskId: true)

let sequencedTask = MockSelfRepeatingTask {
let sequencedTask = MockSelfRepeatingTask(id: 123) {
return 0
}

let handle = executor.executeSequence(from: sequencedTask) { _, _ -> SequenceExecution<Int> in
return .continueSequence(MockSelfRepeatingTask {
return .continueSequence(MockSelfRepeatingTask(id: 123) {
return 0
})
}
Expand All @@ -138,10 +138,11 @@ class ConcurrentSequenceExecutorTests: XCTestCase {
let startTime = CACurrentMediaTime()
do {
_ = try handle.await(withTimeout: 0.5)
} catch SequenceExecutionError.awaitTimeout {
} catch SequenceExecutionError.awaitTimeout(let id) {
didThrowError = true
let endTime = CACurrentMediaTime()
XCTAssertTrue((endTime - startTime) >= 0.5)
XCTAssertEqual(id, 123)
} catch {
XCTFail("Incorrect error thrown: \(error)")
}
Expand All @@ -154,8 +155,9 @@ class MockSelfRepeatingTask: AbstractTask<Int> {

private let execution: () -> Int

init(execution: @escaping () -> Int) {
init(id: Int = nonTrackingDefaultTaskId, execution: @escaping () -> Int) {
self.execution = execution
super.init(id: id)
}

override func execute() -> Int {
Expand Down