forked from shadowfacts/Tusker
51 lines
1.3 KiB
Swift
51 lines
1.3 KiB
Swift
//
|
|
// MultiThreadDictionary.swift
|
|
// Tusker
|
|
//
|
|
// Created by Shadowfacts on 5/6/20.
|
|
// Copyright © 2020 Shadowfacts. All rights reserved.
|
|
//
|
|
|
|
import Foundation
|
|
|
|
class MultiThreadDictionary<Key: Hashable, Value> {
|
|
private let name: String
|
|
private var dict = [Key: Value]()
|
|
private let queue: DispatchQueue
|
|
|
|
init(name: String) {
|
|
self.name = name
|
|
self.queue = DispatchQueue(label: "MultiThreadDictionary (\(name)) Coordinator", attributes: .concurrent)
|
|
}
|
|
|
|
subscript(key: Key) -> Value? {
|
|
get {
|
|
var result: Value? = nil
|
|
queue.sync {
|
|
result = dict[key]
|
|
}
|
|
return result
|
|
}
|
|
set(value) {
|
|
queue.async(flags: .barrier) {
|
|
self.dict[key] = value
|
|
}
|
|
}
|
|
}
|
|
|
|
func removeValueWithoutReturning(forKey key: Key) {
|
|
queue.async(flags: .barrier) {
|
|
self.dict.removeValue(forKey: key)
|
|
}
|
|
}
|
|
|
|
/// If the result of this function is unused, it is preferable to use `removeValueWithoutReturning` as it executes asynchronously and doesn't block the calling thread.
|
|
func removeValue(forKey key: Key) -> Value? {
|
|
var value: Value? = nil
|
|
queue.sync(flags: .barrier) {
|
|
value = dict.removeValue(forKey: key)
|
|
}
|
|
return value
|
|
}
|
|
}
|