Created
September 20, 2018 12:43
-
-
Save s4cha/1516792df973c5f9da4bffc61d021f86 to your computer and use it in GitHub Desktop.
ThreadSafeArray & ThreadSafe<T>
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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