Skip to content

Instantly share code, notes, and snippets.

@rustle
Created February 8, 2018 19:14
Show Gist options
  • Save rustle/45961c756cb1fc45cd0eb70415d39d1d to your computer and use it in GitHub Desktop.
Save rustle/45961c756cb1fc45cd0eb70415d39d1d to your computer and use it in GitHub Desktop.
//
// BoundedQueue.swift
//
// Copyright © 2017 Doug Russell. All rights reserved.
//
import Foundation
public class BoundedQueue {
private let group = DispatchGroup()
private let semaphore: DispatchSemaphore
private let work: DispatchQueue
private let waiting: DispatchQueue
public convenience init(label: String,
count: Int) {
self.init(label: label,
count: count,
qos: .`default`,
autoreleaseFrequency: .workItem)
}
public init(label: String,
count: Int,
qos: DispatchQoS,
autoreleaseFrequency: DispatchQueue.AutoreleaseFrequency) {
work = DispatchQueue(label: label,
qos: qos,
attributes: [.concurrent],
autoreleaseFrequency: autoreleaseFrequency,
target: nil)
waiting = DispatchQueue(label: "\(label).waiting",
qos: qos,
attributes: [],
autoreleaseFrequency: .workItem,
target: work)
semaphore = DispatchSemaphore(value: count)
}
public func async(execute work: @escaping () -> Void) {
group.enter()
waiting.async {
self.semaphore.wait()
self.work.async {
work()
self.semaphore.signal()
self.group.leave()
}
}
}
public func sync<T>(execute work: () throws -> T) rethrows -> T {
group.enter()
return try waiting.sync {
semaphore.wait()
return try self.work.sync {
let result = try work()
semaphore.signal()
group.leave()
return result
}
}
}
}
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment