-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclose_channel.go
65 lines (56 loc) · 1.1 KB
/
close_channel.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
package main
import (
"fmt"
"sync"
"time"
)
func TerminateCallingClose() {
var wg sync.WaitGroup
wg.Add(1)
strChan := make(chan string)
go func() {
for {
element, ok := <-strChan
// check if channel is closed
if !ok {
println("Goroutines killed!")
wg.Done()
return
}
println(element)
}
}()
strChan <- "this"
strChan <- "is"
strChan <- "a"
strChan <- "message"
close(strChan)
// wait all goroutine to stop
wg.Wait()
// print the last message
fmt.Println("This is the end of TerminateCallingClose func!")
}
func TerminateWithChannel() {
fmt.Println("ExampleWithChannel")
quitChan := make(chan bool)
go func() {
for {
select {
case <-quitChan:
return
default:
// print a message every 3 seconds
fmt.Println("Test goroutine")
time.Sleep(time.Second * 3)
}
}
}()
// sleep to print some message from the goroutine
time.Sleep(time.Second * 10)
// stop the goroutine
quitChan <- true
fmt.Println("corountine stopped!")
// test if the gorountine stopped or not
time.Sleep(time.Second * 10)
fmt.Println("End of the TerminateWithChannel")
}