rlocks.nim 1.4 KB

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