1 // Section 11 / acceptance test 18: ring storage is refcounted one per end and
2 // released by whichever side is done with it last. A domain that ends while the
3 // other end is still open must decrement, never free (risk 14: the failure that
4 // only shows up in a test that exercises shutdown under load).
5 //
6 // The order is forced, not raced: the child closes its own handle and returns,
7 // the parent waits for the child's end, and only then closes its handle - so
8 // the parent's drop is the last reference and the release happens on the
9 // parent's own thread, where the segment ledger (per domain, by construction)
10 // can observe it.
11 //
12 //:wasmtest skip
13 package main
14 15 import (
16 "fmt"
17 "runtime"
18 )
19 20 // hold takes one value, closes its own handle (returning its references) and
21 // ends. Its close is the child's drop; the parent's later close is the last.
22 func hold(in chan int32) (closed chan struct{}) {
23 for {
24 select {
25 case <-closed:
26 return closed
27 case v, ok := <-in:
28 _ = v
29 if !ok {
30 return closed
31 }
32 close(in)
33 return closed
34 }
35 }
36 }
37 38 func main() {
39 select {
40 case <-shutdown:
41 return
42 default:
43 }
44 // Chan memory must outlive this frame: the child reads the same channel
45 // storage, so it belongs to the root arena.
46 runtime.SovereignSetArena(runtime.RootArena())
47 in := chan int32{:1}
48 done := spawn(hold, in)
49 50 st0 := runtime.SegmentStats{}
51 runtime.ReadSegmentStats(&st0)
52 if st0.ChanCount != 3 {
53 panic("a spawn with one channel must create three rings: control plus one pair")
54 }
55 56 in <- 1
57 <-done
58 59 // The child dropped its references, but the parent's are still held: the
60 // pair must still be mapped.
61 st1 := runtime.SegmentStats{}
62 runtime.ReadSegmentStats(&st1)
63 if st1.ChanCount != 3 {
64 panic("a ring was released while the parent still held it")
65 }
66 67 // The parent's drop is the last reference; the pair goes, the control ring
68 // (the breaker's, not a channel's) stays.
69 close(in)
70 st2 := runtime.SegmentStats{}
71 runtime.ReadSegmentStats(&st2)
72 if st2.ChanCount != 1 {
73 panic("the closed channel pair's rings were not released by the last end")
74 }
75 fmt.Println("ring release ok", st0.ChanCount, st2.ChanCount)
76 }
77