tshared_ptr_crash.nim 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. discard """
  2. cmd: "nim c --threads:on --gc:arc $file"
  3. action: compile
  4. """
  5. # bug #17893
  6. type
  7. SharedPtr*[T] = object
  8. val: ptr tuple[value: T, atomicCounter: int]
  9. proc `=destroy`*[T](p: var SharedPtr[T]) =
  10. mixin `=destroy`
  11. if p.val != nil:
  12. if atomicLoadN(addr p.val[].atomicCounter, AtomicConsume) == 0:
  13. `=destroy`(p.val[])
  14. deallocShared(p.val)
  15. else:
  16. discard atomicDec(p.val[].atomicCounter)
  17. proc `=copy`*[T](dest: var SharedPtr[T], src: SharedPtr[T]) =
  18. if src.val != nil:
  19. discard atomicInc(src.val[].atomicCounter)
  20. if dest.val != nil:
  21. `=destroy`(dest)
  22. dest.val = src.val
  23. proc newSharedPtr*[T](val: sink T): SharedPtr[T] {.nodestroy.} =
  24. result.val = cast[typeof(result.val)](allocShared(sizeof(result.val[])))
  25. result.val.atomicCounter = 0
  26. result.val.value = val
  27. proc isNil*[T](p: SharedPtr[T]): bool {.inline.} =
  28. p.val == nil
  29. proc `[]`*[T](p: SharedPtr[T]): var T {.inline.} =
  30. when compileOption("boundChecks"):
  31. doAssert(p.val != nil, "deferencing nil shared pointer")
  32. result = p.val.value
  33. type
  34. Sender*[T] = object
  35. queue: SharedPtr[seq[T]]
  36. proc newSender*[T](queue: sink SharedPtr[seq[T]]): Sender[T] =
  37. result = Sender[T](queue: queue)
  38. proc send*[T](self: Sender[T]; t: sink T) =
  39. self.queue[].add t
  40. proc newChannel*(): Sender[int] =
  41. let queue = newSharedPtr(newSeq[int]())
  42. result = newSender(queue)
  43. var
  44. p: Thread[Sender[int]]
  45. proc threadFn(tx: Sender[int]) =
  46. send tx, 0
  47. proc multiThreadedChannel =
  48. let tx = newChannel()
  49. createThread(p, threadFn, tx)
  50. joinThread(p)
  51. multiThreadedChannel()