Mutex+Protector.swift 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  1. //
  2. // Mutex+Protector.swift
  3. //
  4. // Copyright (c) 2014-2017 Alamofire Software Foundation (http://alamofire.org/)
  5. //
  6. // Permission is hereby granted, free of charge, to any person obtaining a copy
  7. // of this software and associated documentation files (the "Software"), to deal
  8. // in the Software without restriction, including without limitation the rights
  9. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  10. // copies of the Software, and to permit persons to whom the Software is
  11. // furnished to do so, subject to the following conditions:
  12. //
  13. // The above copyright notice and this permission notice shall be included in
  14. // all copies or substantial portions of the Software.
  15. //
  16. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  19. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  20. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  21. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  22. // THE SOFTWARE.
  23. //
  24. import Foundation
  25. /// A lock abstraction.
  26. private protocol Lock {
  27. func lock()
  28. func unlock()
  29. func around<T>(_ closure: () -> T) -> T
  30. func around(_ closure: () -> Void)
  31. }
  32. extension Lock {
  33. /// Execute a value producing closure while aquiring the mutex.
  34. ///
  35. /// - Parameter closure: The closure to run.
  36. /// - Returns: The value the closure generated.
  37. func around<T>(_ closure: () -> T) -> T {
  38. lock(); defer { unlock() }
  39. return closure()
  40. }
  41. /// Execute a closure while aquiring the mutex.
  42. ///
  43. /// - Parameter closure: The closure to run.
  44. func around(_ closure: () -> Void) {
  45. lock(); defer { unlock() }
  46. return closure()
  47. }
  48. }
  49. // MARK: -
  50. /// A `pthread_mutex` wrapper, inspired by ProcedureKit.
  51. final class Mutex: Lock {
  52. private var mutex = pthread_mutex_t()
  53. init() {
  54. let result = pthread_mutex_init(&mutex, nil)
  55. precondition(result == 0, "Failed to create pthread mutex")
  56. }
  57. deinit {
  58. let result = pthread_mutex_destroy(&mutex)
  59. assert(result == 0, "Failed to destroy mutex")
  60. }
  61. fileprivate func lock() {
  62. let result = pthread_mutex_lock(&mutex)
  63. assert(result == 0, "Failed to lock mutex")
  64. }
  65. fileprivate func unlock() {
  66. let result = pthread_mutex_unlock(&mutex)
  67. assert(result == 0, "Failed to unlock mutex")
  68. }
  69. }
  70. // MARK: -
  71. /// An `os_unfair_lock` wrapper.
  72. @available (iOS 10.0, macOS 10.12, tvOS 10.0, watchOS 3.0, *)
  73. final class UnfairLock: Lock {
  74. private var unfairLock = os_unfair_lock()
  75. public init() { }
  76. fileprivate func lock() {
  77. os_unfair_lock_lock(&unfairLock)
  78. }
  79. fileprivate func unlock() {
  80. os_unfair_lock_unlock(&unfairLock)
  81. }
  82. }
  83. // MARK: -
  84. /// A thread-safe wrapper around a value.
  85. final class Protector<T> {
  86. private let lock: Lock = {
  87. if #available(iOS 10.0, macOS 10.12, tvOS 10.0, watchOS 3.0, *) {
  88. return UnfairLock()
  89. } else {
  90. return Mutex()
  91. }
  92. }()
  93. private var value: T
  94. init(_ value: T) {
  95. self.value = value
  96. }
  97. /// The contained value. Unsafe for anything more than direct read or write.
  98. var directValue: T {
  99. get { return lock.around { value } }
  100. set { lock.around { value = newValue } }
  101. }
  102. /// Synchronously read or transform the contained value.
  103. ///
  104. /// - Parameter closure: The closure to execute.
  105. /// - Returns: The return value of the closure passed.
  106. func read<U>(_ closure: (T) -> U) -> U {
  107. return lock.around { closure(self.value) }
  108. }
  109. /// Synchronously modify the protected value.
  110. ///
  111. /// - Parameter closure: The closure to execute.
  112. /// - Returns: The modified value.
  113. @discardableResult
  114. func write<U>(_ closure: (inout T) -> U) -> U {
  115. return lock.around { closure(&self.value) }
  116. }
  117. }
  118. extension Protector where T: RangeReplaceableCollection {
  119. func append(_ newElement: T.Iterator.Element) {
  120. write { (ward: inout T) in
  121. ward.append(newElement)
  122. }
  123. }
  124. func append<S: Sequence>(contentsOf newElements: S) where S.Iterator.Element == T.Iterator.Element {
  125. write { (ward: inout T) in
  126. ward.append(contentsOf: newElements)
  127. }
  128. }
  129. func append<C: Collection>(contentsOf newElements: C) where C.Iterator.Element == T.Iterator.Element {
  130. write { (ward: inout T) in
  131. ward.append(contentsOf: newElements)
  132. }
  133. }
  134. }
  135. extension Protector where T: Strideable {
  136. func advance(by stride: T.Stride) {
  137. write { (ward: inout T) in
  138. ward = ward.advanced(by: stride)
  139. }
  140. }
  141. }