Skip to content

Commit 5911d01

Browse files
rmazneakor
authored andcommitted
add an option to limit max concurrency (#21)
* add an option to limit max concurrency * default to Int.max concurrent tasks
1 parent ff40394 commit 5911d01

File tree

1 file changed

+10
-1
lines changed

1 file changed

+10
-1
lines changed

Sources/Concurrency/Executor/ConcurrentSequenceExecutor.swift

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,8 +33,11 @@ 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-
public init(name: String, qos: DispatchQoS = .userInitiated, shouldTrackTaskId: Bool = 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) {
3739
taskQueue = DispatchQueue(label: "Executor.taskQueue-\(name)", qos: qos, attributes: .concurrent)
40+
taskSemaphore = DispatchSemaphore(value: maxConcurrentTasks)
3841
self.shouldTrackTaskId = shouldTrackTaskId
3942
}
4043

@@ -58,10 +61,16 @@ public class ConcurrentSequenceExecutor: SequenceExecutor {
5861
// MARK: - Private
5962

6063
private let taskQueue: DispatchQueue
64+
private let taskSemaphore: DispatchSemaphore
6165
private let shouldTrackTaskId: Bool
6266

6367
private func execute<SequenceResultType>(_ task: Task, with sequenceHandle: SynchronizedSequenceExecutionHandle<SequenceResultType>, _ execution: @escaping (Task, Any) -> SequenceExecution<SequenceResultType>) {
68+
taskSemaphore.wait()
6469
taskQueue.async {
70+
defer {
71+
self.taskSemaphore.signal()
72+
}
73+
6574
guard !sequenceHandle.isCancelled else {
6675
return
6776
}

0 commit comments

Comments
 (0)