Mutex+Protector.swift 5.7 KB

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