ReSwift / ReSwift
1
//
2
//  Synchronized.swift
3
//  ReSwift
4
//
5
//  Created by Basem Emara on 2020-08-18.
6
//  https://basememara.com/creating-thread-safe-generic-values-in-swift/
7
//
8
//  Copyright © 2020 ReSwift Community. All rights reserved.
9
//
10

11
import Foundation
12

13
/// An object that manages the execution of tasks atomically.
14
struct Synchronized<Value> {
15 5
    private let mutex = DispatchQueue(label: "reswift.github.io.ReSwift.Utils.Synchronized", attributes: .concurrent)
16
    private var _value: Value
17 6
    init(_ value: Value) {
18 6
        self._value = value
19
    }
20
    /// Returns or modify the thread-safe value.
21 6
    var value: Value { return mutex.sync { return _value } }
22
    /// Submits a block for synchronous, thread-safe execution.
23 6
    mutating func value<T>(execute task: (inout Value) throws -> T) rethrows -> T {
24 6
        return try mutex.sync(flags: .barrier) { return try task(&_value) }
25
    }
26
}

Read our documentation on viewing source code .

Loading