Skip to content

Instantly share code, notes, and snippets.

@s4cha
Created September 20, 2018 12:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save s4cha/1516792df973c5f9da4bffc61d021f86 to your computer and use it in GitHub Desktop.
Save s4cha/1516792df973c5f9da4bffc61d021f86 to your computer and use it in GitHub Desktop.
ThreadSafeArray & ThreadSafe<T>
//
// ThreadSafe.swift
// ThreadSafeArray
//
// Created by Sacha DSO on 20/09/2018.
// Copyright © 2018 freshOS. All rights reserved.
//
import Foundation
class ThreadSafeArray<T> {
private var threadSafeArray: ThreadSafe<[T]>
init() {
self.threadSafeArray = ThreadSafe(value: [T]())
}
public func append(_ newElement: T) {
threadSafeArray.write { arr in
arr.append(newElement)
}
}
public func remove(where clause: @escaping (T) -> Bool) {
threadSafeArray.write { arr in
if let index = arr.index(where: clause) {
arr.remove(at: index)
}
}
}
public var array: [T] {
return threadSafeArray.read()
}
}
class ThreadSafe<T> {
var value:T!
init(value: T) {
self.value = value
}
private let queue = DispatchQueue(label: "ThreadSafeArrayQueue", attributes: .concurrent)
func write(callback:@escaping (inout T) -> Void) {
queue.async(flags: .barrier) { [weak self] in
if let strongSelf = self {
callback(&strongSelf.value)
}
}
}
func read() -> T {
return queue.sync { value }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment