Mutex.swift 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. /*
  2. * Copyright 2016, gRPC Authors All rights reserved.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #if SWIFT_PACKAGE
  17. import CgRPC
  18. #endif
  19. /// A general-purpose Mutex used to synchronize gRPC operations
  20. /// but it can be used anywhere
  21. public class Mutex {
  22. /// Pointer to underlying C representation
  23. private let underlyingMutex: UnsafeMutableRawPointer
  24. /// Initializes a Mutex
  25. public init() {
  26. underlyingMutex = cgrpc_mutex_create()
  27. }
  28. deinit {
  29. cgrpc_mutex_destroy(underlyingMutex)
  30. }
  31. /// Locks a Mutex
  32. ///
  33. /// Waits until no thread has a lock on the Mutex,
  34. /// causes the calling thread to own an exclusive lock on the Mutex,
  35. /// then returns.
  36. ///
  37. /// May block indefinitely or crash if the calling thread has a lock on the Mutex.
  38. public func lock() {
  39. cgrpc_mutex_lock(underlyingMutex)
  40. }
  41. /// Unlocks a Mutex
  42. ///
  43. /// Releases an exclusive lock on the Mutex held by the calling thread.
  44. public func unlock() {
  45. cgrpc_mutex_unlock(underlyingMutex)
  46. }
  47. /// Runs a block within a locked mutex
  48. ///
  49. /// Parameter block: the code to run while the mutex is locked
  50. public func synchronize(block: () throws -> Void) rethrows {
  51. lock()
  52. try block()
  53. unlock()
  54. }
  55. }