rlocks.nim 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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. {.error: "Rlocks requires --threads:on option.".}
  12. const insideRLocksModule = true
  13. include "system/syslocks"
  14. type
  15. RLock* = SysLock ## Nim lock, re-entrant
  16. proc initRLock*(lock: var RLock) {.inline.} =
  17. ## Initializes the given lock.
  18. when defined(posix):
  19. var a: SysLockAttr
  20. initSysLockAttr(a)
  21. setSysLockType(a, SysLockType_Reentrant)
  22. initSysLock(lock, a.addr)
  23. else:
  24. initSysLock(lock)
  25. proc deinitRLock*(lock: var RLock) {.inline.} =
  26. ## Frees the resources associated with the lock.
  27. deinitSys(lock)
  28. proc tryAcquire*(lock: var RLock): bool {.inline.} =
  29. ## Tries to acquire the given lock. Returns `true` on success.
  30. result = tryAcquireSys(lock)
  31. proc acquire*(lock: var RLock) {.inline.} =
  32. ## Acquires the given lock.
  33. acquireSys(lock)
  34. proc release*(lock: var RLock) {.inline.} =
  35. ## Releases the given lock.
  36. releaseSys(lock)
  37. template withRLock*(lock: var RLock, code: untyped): untyped =
  38. ## Acquires the given lock and then executes the code.
  39. acquire(lock)
  40. {.locks: [lock].}:
  41. try:
  42. code
  43. finally:
  44. release(lock)