Skip to content

Atomic variables in Swift #4

@fespinoza

Description

@fespinoza

It basically means that reading and writing on a property will happen in an atomic way (one operation), then preventing reading outdated values when a writing is occurring and so on.

// A wrapper for values in order to make their reading/writing atomic
final class Atomic<Value> {
    private let queue = DispatchQueue(label: "my.queue.name")
    private var _value: Value

    init(value: Value) {
        self._value = value
    }

    var value: Value {
        return queue.sync {
            self._value
        }
    }

    func mutate(_ transform: (inout Value) -> Void) {
        queue.sync {
            transform(&self._value)
        }
    }
}

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions