Monday, 4 November 2019

Is reading a 64-bit atomic value safe on 64-bit platforms if I write/swap using OS atomic functions with barrier?

The question is about the latest iOS and macOS. Suppose I have the following implementation for an atomic Int64 in Swift:

struct AtomicInt64 {

    private var _value: Int64 = 0

    init(_ value: Int64) {
        set(value)
    }

    mutating func set(_ newValue: Int64) {
        while !OSAtomicCompareAndSwap64Barrier(_value, newValue, &_value) { }
    }

    mutating func setIf(expectedValue: Int64, _ newValue: Int64) -> Bool {
        return OSAtomicCompareAndSwap64Barrier(expectedValue, newValue, &_value)
    }

    var value: Int64 { _value }
}

Note the value accessor: is it safe?

If not, what should I do to fetch the value atomically?

Also, would the 32-bit version of the same class be safe?

Edit please note that the question is language agnostic. The above could have been written in any language that generates CPU instructions.



from Is reading a 64-bit atomic value safe on 64-bit platforms if I write/swap using OS atomic functions with barrier?

No comments:

Post a Comment