rlocks.nim 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. #
  2. #
  3. # Nim's Runtime Library
  4. # (c) Copyright 2016 Anatoly Galiulin
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. ## This module contains Nim's support for reentrant locks.
  10. when not compileOption("threads") and not defined(nimdoc):
  11. when false:
  12. # make rlocks modlue consistent with locks module,
  13. # so they can replace each other seamlessly.
  14. {.error: "Rlocks requires --threads:on option.".}
  15. const insideRLocksModule = true
  16. include "system/syslocks"
  17. type
  18. RLock* = SysLock ## Nim lock, re-entrant
  19. proc initRLock*(lock: var RLock) {.inline.} =
  20. ## Initializes the given lock.
  21. when defined(posix):
  22. var a: SysLockAttr
  23. initSysLockAttr(a)
  24. setSysLockType(a, SysLockType_Reentrant)
  25. initSysLock(lock, a.addr)
  26. else:
  27. initSysLock(lock)
  28. proc deinitRLock*(lock: var RLock) {.inline.} =
  29. ## Frees the resources associated with the lock.
  30. deinitSys(lock)
  31. proc tryAcquire*(lock: var RLock): bool {.inline.} =
  32. ## Tries to acquire the given lock. Returns `true` on success.
  33. result = tryAcquireSys(lock)
  34. proc acquire*(lock: var RLock) {.inline.} =
  35. ## Acquires the given lock.
  36. acquireSys(lock)
  37. proc release*(lock: var RLock) {.inline.} =
  38. ## Releases the given lock.
  39. releaseSys(lock)
  40. template withRLock*(lock: RLock, code: untyped) =
  41. ## Acquires the given lock and then executes the code.
  42. acquire(lock)
  43. {.locks: [lock].}:
  44. try:
  45. code
  46. finally:
  47. release(lock)