tguard1.nim 657 B

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. discard """
  2. output: "90"
  3. """
  4. when false:
  5. template lock(a, b: ptr Lock; body: stmt) =
  6. if cast[ByteAddress](a) < cast[ByteAddress](b):
  7. pthread_mutex_lock(a)
  8. pthread_mutex_lock(b)
  9. else:
  10. pthread_mutex_lock(b)
  11. pthread_mutex_lock(a)
  12. {.locks: [a, b].}:
  13. try:
  14. body
  15. finally:
  16. pthread_mutex_unlock(a)
  17. pthread_mutex_unlock(b)
  18. type
  19. ProtectedCounter[T] = object
  20. i {.guard: L.}: T
  21. L: int
  22. var
  23. c: ProtectedCounter[int]
  24. c.i = 89
  25. template atomicRead(L, x): untyped =
  26. {.locks: [L].}:
  27. x
  28. proc main =
  29. {.locks: [c.L].}:
  30. inc c.i
  31. discard
  32. echo(atomicRead(c.L, c.i))
  33. main()