locks.nim 2.1 KB

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