<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/xhtml; charset=utf-8">
</head>
<body>
<div style="font-family:sans-serif"><div style="white-space:normal">
<p dir="auto">Hey all-</p>
<p dir="auto">I used Erica's queue example (<a href="http://ericasadun.com/2016/03/08/swift-queue-fun/" style="color:#3983C4">http://ericasadun.com/2016/03/08/swift-queue-fun/</a>) to implement a queue in a multi-threaded Swift app (quick aside, is it 'correct' to say multithreaded when using DispatchQueue?). I spawn a number of objects on a .concurrent DispatchQueue and they all throw strings into the queue, where the main thread pops from the queue and prints it out.</p>
<p dir="auto">In C/C++ I'd create a mutex and use that for pushing and popping. In Swift 3 I did wrapped the methods in a serial queue:</p>
<p dir="auto">let serialQueue = DispatchQueue(label: "log.queue")</p>
<p dir="auto">// <a href="http://ericasadun.com/2016/03/08/swift-queue-fun/" style="color:#3983C4">http://ericasadun.com/2016/03/08/swift-queue-fun/</a><br>
public struct Queue<T>: ExpressibleByArrayLiteral {<br>
/// backing array store<br>
public private(set) var elements: Array<T> = []</p>
<pre style="background-color:#F7F7F7; border-radius:5px 5px 5px 5px; margin-left:15px; margin-right:15px; max-width:90vw; overflow-x:auto; padding:5px" bgcolor="#F7F7F7"><code style="background-color:#F7F7F7; border-radius:3px; margin:0; padding:0" bgcolor="#F7F7F7">/// introduce a new element to the queue in O(1) time
public mutating func push(_ value: T) {
serialQueue.sync {
elements.append(value)
}
}
/// remove the front of the queue in O(`count` time
public mutating func pop() -> T? {
var retValue: T? = nil
serialQueue.sync {
if isEmpty == false {
retValue = elements.removeFirst()
}
}
return retValue
}
/// test whether the queue is empty
public var isEmpty: Bool { return elements.isEmpty }
/// queue size, computed property
public var count: Int {
var count: Int = 0
serialQueue.sync {
count = elements.count
}
return count
}
/// offer `ArrayLiteralConvertible` support
public init(arrayLiteral elements: T...) {
serialQueue.sync {
self.elements = elements
}
}
</code></pre>
<p dir="auto">}</p>
<p dir="auto">This is working; I have tested it with 50, uh, threads, and have had zero problems. So I'm content to go on my merry way and use it, but wanted to get some thoughts about whether this is the 'right' way and if there is something more Swift-y/libDispatch-y that I should use instead. </p>
<p dir="auto">Thanks for any info,</p>
<p dir="auto">Ron</p>
</div>
</div>
</body>
</html>