Mutex/queue access in Swift 3


(Ron Olson) #1

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


(Adrian Zubarev) #2

Do you care about the order in which your queue is filled?
Do you have multiple queues - I’m asking because your serial queue is not part of Queue<T>?!
You could add your DispatchQueue right into Queue<T>. It depends on your situation and your goal but sometime you could optimise your code with something like self._queue.async(flags: .barrier) { … }.

This required a concurrent dispatch queue, it will not block (like sync does) but it won’t run asynchronously with any other task in your dispatch queue (flags: .barrier).

···

--
Adrian Zubarev
Sent with Airmail

Am 23. September 2016 um 17:34:56, Ron Olson via swift-users (swift-users@swift.org) schrieb:

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


(Adrian Zubarev) #3

Whops sry wrong receiver mail. :confused: My bad.

···

--
Adrian Zubarev
Sent with Airmail

Am 23. September 2016 um 17:51:44, Adrian Zubarev (adrian.zubarev@devandartist.com) schrieb:

Do you care about the order in which your queue is filled?
Do you have multiple queues - I’m asking because your serial queue is not part of Queue<T>?!
You could add your DispatchQueue right into Queue<T>. It depends on your situation and your goal but sometime you could optimise your code with something like self._queue.async(flags: .barrier) { … }.

This required a concurrent dispatch queue, it will not block (like sync does) but it won’t run asynchronously with any other task in your dispatch queue (flags: .barrier).

--
Adrian Zubarev
Sent with Airmail

Am 23. September 2016 um 17:34:56, Ron Olson via swift-users (swift-users@swift.org) schrieb:

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