locks.nim 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. #
  2. #
  3. # Nim's Runtime Library
  4. # (c) Copyright 2015 Andreas Rumpf
  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 locks and condition vars.
  10. when not compileOption("threads") and not defined(nimdoc):
  11. when false: # fix #12330
  12. {.error: "Locks requires --threads:on option.".}
  13. const insideRLocksModule = false
  14. include "system/syslocks"
  15. type
  16. Lock* = SysLock ## Nim lock; whether this is re-entrant
  17. ## or not is unspecified!
  18. Cond* = SysCond ## Nim condition variable
  19. {.push stackTrace: off.}
  20. proc initLock*(lock: var Lock) {.inline.} =
  21. ## Initializes the given lock.
  22. initSysLock(lock)
  23. proc deinitLock*(lock: var Lock) {.inline.} =
  24. ## Frees the resources associated with the lock.
  25. deinitSys(lock)
  26. proc tryAcquire*(lock: var Lock): bool =
  27. ## Tries to acquire the given lock. Returns `true` on success.
  28. result = tryAcquireSys(lock)
  29. proc acquire*(lock: var Lock) =
  30. ## Acquires the given lock.
  31. acquireSys(lock)
  32. proc release*(lock: var Lock) =
  33. ## Releases the given lock.
  34. releaseSys(lock)
  35. proc initCond*(cond: var Cond) {.inline.} =
  36. ## Initializes the given condition variable.
  37. initSysCond(cond)
  38. proc deinitCond*(cond: var Cond) {.inline.} =
  39. ## Frees the resources associated with the lock.
  40. deinitSysCond(cond)
  41. proc wait*(cond: var Cond, lock: var Lock) {.inline.} =
  42. ## waits on the condition variable `cond`.
  43. waitSysCond(cond, lock)
  44. proc signal*(cond: var Cond) {.inline.} =
  45. ## sends a signal to the condition variable `cond`.
  46. signalSysCond(cond)
  47. template withLock*(a: Lock, body: untyped) =
  48. ## Acquires the given lock, executes the statements in body and
  49. ## releases the lock after the statements finish executing.
  50. mixin acquire, release
  51. acquire(a)
  52. {.locks: [a].}:
  53. try:
  54. body
  55. finally:
  56. release(a)
  57. {.pop.}