@@ -3,6 +3,7 @@ package main
33import (
44 "runtime"
55 "sync"
6+ "sync/atomic"
67 "time"
78)
89
@@ -70,11 +71,13 @@ func main() {
7071 // Test multi-receiver.
7172 ch = make (chan int )
7273 wg .Add (3 )
73- go fastreceiver (ch )
74- go fastreceiver (ch )
75- go fastreceiver (ch )
74+ var result atomic.Uint32
75+ go fastreceiveradd (ch , & result )
76+ go fastreceiveradd (ch , & result )
77+ go fastreceiveradd (ch , & result )
7678 slowsender (ch )
7779 wg .Wait ()
80+ println ("sum of sums:" , result .Load ())
7881
7982 // Test iterator style channel.
8083 ch = make (chan int )
@@ -88,7 +91,10 @@ func main() {
8891 println ("sum(100):" , sum )
8992
9093 // Test simple selects.
91- go selectDeadlock () // cannot use waitGroup here - never terminates
94+ wg .Add (1 )
95+ go selectDeadlock ()
96+ wg .Wait ()
97+
9298 wg .Add (1 )
9399 go selectNoOp ()
94100 wg .Wait ()
@@ -244,7 +250,7 @@ func receive(ch <-chan int) {
244250func sender (ch chan int ) {
245251 for i := 1 ; i <= 8 ; i ++ {
246252 if i == 4 {
247- time .Sleep (time .Microsecond )
253+ time .Sleep (time .Millisecond )
248254 println ("slept" )
249255 }
250256 ch <- i
@@ -290,6 +296,16 @@ func fastreceiver(ch chan int) {
290296 wg .Done ()
291297}
292298
299+ func fastreceiveradd (ch chan int , result * atomic.Uint32 ) {
300+ sum := 0
301+ for i := 0 ; i < 2 ; i ++ {
302+ n := <- ch
303+ sum += n
304+ }
305+ result .Add (uint32 (sum ))
306+ wg .Done ()
307+ }
308+
293309func iterator (ch chan int , top int ) {
294310 for i := 0 ; i < top ; i ++ {
295311 ch <- i
@@ -300,6 +316,7 @@ func iterator(ch chan int, top int) {
300316
301317func selectDeadlock () {
302318 println ("deadlocking" )
319+ wg .Done ()
303320 select {}
304321 println ("unreachable" )
305322}
0 commit comments