Mutex+Protector.swift 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198
  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. /// Execute a value producing closure while aquiring the mutex.
  70. ///
  71. /// - Parameter closure: The closure to run.
  72. /// - Returns: The value the closure generated.
  73. func around<T>(_ closure: () -> T) -> T {
  74. lock(); defer { unlock() }
  75. return closure()
  76. }
  77. /// Execute a closure while aquiring the mutex.
  78. ///
  79. /// - Parameter closure: The closure to run.
  80. func around(_ closure: () -> Void) {
  81. lock(); defer { unlock() }
  82. return closure()
  83. }
  84. }
  85. /// An `os_unfair_lock` wrapper.
  86. @available (iOS 10.0, macOS 10.12, tvOS 10.0, watchOS 3.0, *)
  87. final class UnfairLock: Lock {
  88. private var unfairLock = os_unfair_lock()
  89. public init() { }
  90. fileprivate func lock() {
  91. os_unfair_lock_lock(&unfairLock)
  92. }
  93. fileprivate func unlock() {
  94. os_unfair_lock_unlock(&unfairLock)
  95. }
  96. /// Execute a value producing closure while aquiring the lock.
  97. ///
  98. /// - Parameter closure: The closure to run.
  99. /// - Returns: The value the closure generated.
  100. func around<T>(_ closure: () -> T) -> T {
  101. lock(); defer { unlock() }
  102. return closure()
  103. }
  104. /// Execute a closure while aquiring the lock.
  105. ///
  106. /// - Parameter closure: The closure to run.
  107. func around(_ closure: () -> Void) {
  108. lock(); defer { unlock() }
  109. return closure()
  110. }
  111. }
  112. /// A thread-safe wrapper around a value.
  113. final class Protector<T> {
  114. private let lock: Lock = {
  115. if #available(iOS 10.0, macOS 10.12, tvOS 10.0, watchOS 3.0, *) {
  116. return UnfairLock()
  117. } else {
  118. return Mutex()
  119. }
  120. }()
  121. private var value: T
  122. init(_ value: T) {
  123. self.value = value
  124. }
  125. /// The contained value. Unsafe for anything more than direct read or write.
  126. var directValue: T {
  127. get { return lock.around { value } }
  128. set { lock.around { value = newValue } }
  129. }
  130. /// Synchronously read or transform the contained value.
  131. ///
  132. /// - Parameter closure: The closure to execute.
  133. /// - Returns: The return value of the closure passed.
  134. func read<U>(_ closure: (T) -> U) -> U {
  135. return lock.around { closure(self.value) }
  136. }
  137. /// Synchronously modify the protected value.
  138. ///
  139. /// - Parameter closure: The closure to execute.
  140. /// - Returns: The modified value.
  141. @discardableResult
  142. func write<U>(_ closure: (inout T) -> U) -> U {
  143. return lock.around { closure(&self.value) }
  144. }
  145. }
  146. extension Protector where T: RangeReplaceableCollection {
  147. func append(_ newElement: T.Iterator.Element) {
  148. write { (ward: inout T) in
  149. ward.append(newElement)
  150. }
  151. }
  152. func append<S: Sequence>(contentsOf newElements: S) where S.Iterator.Element == T.Iterator.Element {
  153. write { (ward: inout T) in
  154. ward.append(contentsOf: newElements)
  155. }
  156. }
  157. func append<C: Collection>(contentsOf newElements: C) where C.Iterator.Element == T.Iterator.Element {
  158. write { (ward: inout T) in
  159. ward.append(contentsOf: newElements)
  160. }
  161. }
  162. }
  163. extension Protector where T: Strideable {
  164. func advance(by stride: T.Stride) {
  165. write { (ward: inout T) in
  166. ward = ward.advanced(by: stride)
  167. }
  168. }
  169. }