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
_______________________________________________
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users

Reply via email to