-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathChan_N_senders_wg.go
78 lines (62 loc) · 1.03 KB
/
Chan_N_senders_wg.go
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package main
import (
"fmt"
"runtime"
"strconv"
"sync"
"sync/atomic"
"time"
)
var (
flag int64 = 0
wg = new(sync.WaitGroup)
c = make(chan string)
)
func Recv(n int) {
for {
select {
case data, ok := <-c:
if !ok {
fmt.Println("Receiver ", n, " left.")
return
}
fmt.Println("Receiver ", n, " received:", data)
}
//runtime.Gosched()
}
}
func Send(n int) {
defer wg.Done()
for i := 0; ; i++ {
if atomic.LoadInt64(&flag) == 1 {
fmt.Println("Sender ", n, " left.")
return
}
time.Sleep(time.Millisecond * 100)
data := "<data " + strconv.Itoa(i) + "> from Sender" + strconv.Itoa(n)
c <- data
}
}
func Close() {
atomic.CompareAndSwapInt64(&flag, 0, 1)
wg.Wait()
close(c)
}
func main() {
runtime.GOMAXPROCS(4)
fmt.Println("Started...")
go Recv(1)
go Recv(2)
go Recv(3)
wg.Add(1)
go Send(1)
wg.Add(1)
go Send(2)
wg.Add(1)
go Send(3)
time.Sleep(time.Millisecond * 1000)
fmt.Println("Prepare to done..")
Close()
fmt.Println("Done!")
time.Sleep(1e10 * 2)
}