locks.nim 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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. {.push stackTrace: off.}
  17. proc initLock*(lock: var Lock) {.inline.} =
  18. ## Initializes the given lock.
  19. initSysLock(lock)
  20. proc deinitLock*(lock: var Lock) {.inline.} =
  21. ## Frees the resources associated with the lock.
  22. deinitSys(lock)
  23. proc tryAcquire*(lock: var Lock): bool =
  24. ## Tries to acquire the given lock. Returns `true` on success.
  25. result = tryAcquireSys(lock)
  26. proc acquire*(lock: var Lock) =
  27. ## Acquires the given lock.
  28. acquireSys(lock)
  29. proc release*(lock: var Lock) =
  30. ## Releases the given lock.
  31. releaseSys(lock)
  32. proc initCond*(cond: var Cond) {.inline.} =
  33. ## Initializes the given condition variable.
  34. initSysCond(cond)
  35. proc deinitCond*(cond: var Cond) {.inline.} =
  36. ## Frees the resources associated with the lock.
  37. deinitSysCond(cond)
  38. proc wait*(cond: var Cond, lock: var Lock) {.inline.} =
  39. ## waits on the condition variable `cond`.
  40. waitSysCond(cond, lock)
  41. proc signal*(cond: var Cond) {.inline.} =
  42. ## sends a signal to the condition variable `cond`.
  43. signalSysCond(cond)
  44. template withLock*(a: Lock, body: untyped) =
  45. ## Acquires the given lock, executes the statements in body and
  46. ## releases the lock after the statements finish executing.
  47. mixin acquire, release
  48. a.acquire()
  49. {.locks: [a].}:
  50. try:
  51. body
  52. finally:
  53. a.release()
  54. {.pop.}