locks.nim 1.8 KB

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