Skip to content

Commit 4c21014

Browse files
neakorrudro
authored andcommitted
Avoid using semaphore if there is no concurrency limit (#22)
Avoid paying the cost of calling the semaphore if no limit is set.
1 parent 5911d01 commit 4c21014

File tree

1 file changed

+16
-9
lines changed

1 file changed

+16
-9
lines changed

Sources/Concurrency/Executor/ConcurrentSequenceExecutor.swift

Lines changed: 16 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -33,11 +33,16 @@ public class ConcurrentSequenceExecutor: SequenceExecutor {
3333
/// reported error contains the ID of the task that was being executed
3434
/// when the timeout occurred. The tracking does incur a minor
3535
/// performance cost. This value defaults to `false`.
36-
/// - parameter maxConcurrentTasks: limits the maximum number of tasks
37-
/// run concurrently. Defaults to Int.max.
38-
public init(name: String, qos: DispatchQoS = .userInitiated, shouldTrackTaskId: Bool = false, maxConcurrentTasks: Int = Int.max) {
36+
/// - parameter maxConcurrentTasks: The optional maximum number of tasks
37+
/// the executor can execute concurrently. `nil` if the executor should
38+
/// not limit the maximum number of concurrent tasks. Defaults to `nil`.
39+
public init(name: String, qos: DispatchQoS = .userInitiated, shouldTrackTaskId: Bool = false, maxConcurrentTasks: Int? = nil) {
3940
taskQueue = DispatchQueue(label: "Executor.taskQueue-\(name)", qos: qos, attributes: .concurrent)
40-
taskSemaphore = DispatchSemaphore(value: maxConcurrentTasks)
41+
if let maxConcurrentTasks = maxConcurrentTasks {
42+
taskSemaphore = DispatchSemaphore(value: maxConcurrentTasks)
43+
} else {
44+
taskSemaphore = nil
45+
}
4146
self.shouldTrackTaskId = shouldTrackTaskId
4247
}
4348

@@ -61,16 +66,18 @@ public class ConcurrentSequenceExecutor: SequenceExecutor {
6166
// MARK: - Private
6267

6368
private let taskQueue: DispatchQueue
64-
private let taskSemaphore: DispatchSemaphore
69+
private let taskSemaphore: DispatchSemaphore?
6570
private let shouldTrackTaskId: Bool
6671

6772
private func execute<SequenceResultType>(_ task: Task, with sequenceHandle: SynchronizedSequenceExecutionHandle<SequenceResultType>, _ execution: @escaping (Task, Any) -> SequenceExecution<SequenceResultType>) {
68-
taskSemaphore.wait()
73+
taskSemaphore?.wait()
6974
taskQueue.async {
70-
defer {
71-
self.taskSemaphore.signal()
75+
if let taskSemaphore = self.taskSemaphore {
76+
defer {
77+
taskSemaphore.signal()
78+
}
7279
}
73-
80+
7481
guard !sequenceHandle.isCancelled else {
7582
return
7683
}

0 commit comments

Comments
 (0)