forked from nim-lang/threading
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtsmartptrsleak.nim
More file actions
55 lines (45 loc) · 1.12 KB
/
tsmartptrsleak.nim
File metadata and controls
55 lines (45 loc) · 1.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import threading/smartptrs
import std/isolation
import std/locks
import std/atomics
import threading/channels
var
freeCounts: Atomic[int]
type
TestObj = object
when defined(nimAllowNonVarDestructor):
proc `=destroy`(obj: TestObj) =
discard freeCounts.fetchAdd(1, moRelease)
else:
proc `=destroy`(obj: var TestObj) =
discard freeCounts.fetchAdd(1, moRelease)
var
thr: array[0..1, Thread[void]]
chan = newChan[SharedPtr[TestObj]]()
const
# N = 10_000_000
# doSleep = false
N = 10_000
doSleep = true
import std/os
proc threadA() {.thread.} =
for i in 1..N:
block:
var a: SharedPtr[TestObj] = newSharedPtr(unsafeIsolate TestObj())
var b = a
chan.send(b)
doAssert a.isNil == false # otherwise we don't copy a?
when doSleep:
os.sleep(1)
proc threadB() {.thread.} =
for i in 1..N:
block:
var b: SharedPtr[TestObj] = chan.recv()
when doSleep:
os.sleep(1)
createThread(thr[0], threadA)
createThread(thr[1], threadB)
joinThreads(thr)
echo "freeCounts: got: ", load(freeCounts, moRelaxed), " expected: ", N
echo ""
assert freeCounts.load(moRelaxed) == N