twrong_refcounts.nim 830 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. discard """
  2. output: "Success"
  3. """
  4. import math, random, threadPool
  5. # ---
  6. type
  7. Person = object
  8. age: int
  9. friend: ref Person
  10. var
  11. people: seq[ref Person] = @[]
  12. proc newPerson(age:int): ref Person =
  13. result.new()
  14. result.age = age
  15. proc greet(p:Person) =
  16. #echo p.age, ", ", p.friend.age
  17. p.friend.age += 1
  18. # ---
  19. proc setup =
  20. for i in 0 .. <20:
  21. people.add newPerson(i + 1)
  22. for i in 0 .. <20:
  23. people[i].friend = people[random(20)]
  24. proc update =
  25. var countA: array[20, int]
  26. var countB: array[20, int]
  27. for i, p in people:
  28. countA[i] = getRefCount(p)
  29. parallel:
  30. for i in 0 .. people.high:
  31. spawn greet(people[i][])
  32. for i, p in people:
  33. countB[i] = getRefCount(p)
  34. for i in 0 .. <20:
  35. doAssert countA[i] == countB[i]
  36. echo "Success"
  37. # ---
  38. when true:
  39. setup()
  40. update()