并发阻塞队列

时间:2019-02-22 01:27:46

标签: swift concurrency

我正在尝试解决生产者-消费者问题,但是我希望我的使用者线程阻塞直到数据可用。我有几个线程在生成数据,但是只有一个线程在使用它。将项目快速添加到数组中时,出现“线程4:致命错误:索引超出范围” @“结果= self.array.remove(at:0)”。一次添加一个项目(例如,缓慢地添加500毫秒以上)时,它会按预期工作。在c#中,使用Monitor.Wait()/ Pulse()似乎很简单。我怎样才能使它迅速工作?预先感谢。

let consume: DispatchQueue = DispatchQueue.global(qos: .userInteractive)
            consume.async {
                while self.mConnect {
                    let dg = self.queue.take()//block until item is available
                    //do something
                }
            }

...

public class SynchronizedQueue<Element> {
fileprivate let semaphore = DispatchSemaphore(value: 0)
fileprivate let queue = DispatchQueue(label: "fooBar", attributes: .concurrent)
fileprivate var array = [Element]()
private var isWaiting : Bool = false
func take() -> Element {
    var result : Element!
    queue.sync {
        if self.array.count == 0 {
            print("Waiting...")
            self.isWaiting = true
            self.semaphore.wait()
        }
        self.isWaiting = false
        print("Not waiting count = \(self.array.count)")
        result = self.array.remove(at: 0)
    }
    return result
}

func add(_ element : Element) {
    queue.sync {
        self.array.append(element)
        if self.isWaiting {
            self.semaphore.signal()
        }
    }
}

}

0 个答案:

没有答案