swift实现阻塞队列 swift实现简易阻塞队列 1234567891011121314151617181920212223242526272829303132333435363738import Foundation//阻塞队列class BlockingQueue<T>{ private var queue : [T] private let capacity : Int private let queueAccess = DispatchQueue(label: "BlockingQueue.queueAccess") private let emptySemaphore : DispatchSemaphore private let fullSemaphore : DispatchSemaphore init(_ capacity : Int) { self.queue = [] self.capacity = capacity self.emptySemaphore = DispatchSemaphore(value: 0) self.fullSemaphore = DispatchSemaphore(value: capacity) } //放入一个元素 func put(_ element : T){ fullSemaphore.wait() queueAccess.sync { self.queue.append(element) } emptySemaphore.signal() } //取出一个元素 func take() -> T{ emptySemaphore.wait() let element = queueAccess.sync { let item = self.queue.removeFirst() return item } fullSemaphore.signal() return element }}