Skip to content

Instantly share code, notes, and snippets.

@christopher-fuller
Created November 4, 2016 19:18
Show Gist options
  • Save christopher-fuller/35108deb00291085f38b8b390fa80878 to your computer and use it in GitHub Desktop.
Save christopher-fuller/35108deb00291085f38b8b390fa80878 to your computer and use it in GitHub Desktop.
//
// ReadersWriterLock.swift
// Created by Christopher Fuller for Southern California Public Radio
// Original version at https://github.com/SCPR/swift-experiments/blob/master/source/ReadersWriterLock.swift
// Updated by Christopher Fuller for Swift 3 compatibility
//
// Copyright (c) 2016 Southern California Public Radio
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
class ReadersWriterLock<T> {
var value: T? {
get {
var value: T?
queue.sync {
value = synchronizedValue
}
return value
}
set {
set(value: newValue)
}
}
private var synchronizedValue: T?
private let queue: DispatchQueue
init(queueLabel label: String) {
queue = DispatchQueue(label: label, attributes: .concurrent)
}
convenience init() {
self.init(queueLabel: "ReadersWriterLock")
}
func set(value: T?) {
queue.sync(flags: .barrier) {
synchronizedValue = value
}
}
func setAsync(value: T?, completion: ((T?) -> Void)? = nil) {
queue.async(flags: .barrier) {
[ weak self ] in
guard let _self = self else { return }
_self.synchronizedValue = value
completion?(value)
}
}
}
@christopher-fuller
Copy link
Author

Example Usage

let lock = ReadersWriterLock<String>() // String is just for example, can be any type.

Set value asynchronously:

lock.setAsync(value: "Hello World!")

Set value synchronously:

lock.value = "Hello World!" // equivalent to: lock.set(value: "Hello World!")

Read value (only synchronous obviously):

let _ = lock.value

See https://en.wikipedia.org/wiki/Readers–writer_lock for more information.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment