[swift-users] Mutex/queue access in Swift 3

Ron Olson tachoknight at gmail.com
Fri Sep 23 10:34:44 CDT 2016


Hey all-

I used Erica's queue example 
(http://ericasadun.com/2016/03/08/swift-queue-fun/) 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.

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:

let serialQueue = DispatchQueue(label: "log.queue")

// http://ericasadun.com/2016/03/08/swift-queue-fun/
public struct Queue<T>: ExpressibleByArrayLiteral {
     /// backing array store
     public private(set) var elements: Array<T> = []

     /// 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
         }
     }
}

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.

Thanks for any info,

Ron
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20160923/d39cff9f/attachment.html>


More information about the swift-users mailing list