forked from ardanlabs/gotraining
-
Notifications
You must be signed in to change notification settings - Fork 0
/
example1.go
67 lines (53 loc) · 1.53 KB
/
example1.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
// All material is licensed under the Apache License Version 2.0, January 2004
// http://www.apache.org/licenses/LICENSE-2.0
// Sample program to show the order of channel communication for unbuffered,
// buffered and closing channels based on the specification.
// https://golang.org/ref/mem#tmp_7
package main
func main() {
unBuffered()
buffered()
closed()
}
// With unbuffered channels, the receive happens before the corresponding send.
// The write to a happens before the receive on c, which happens before the
// corresponding send on c completes, which happens before the print.
func unBuffered() {
c := make(chan int)
var a string
go func() {
a = "hello, world"
<-c
}()
c <- 0
// We are guaranteed to print "hello, world".
println(a)
}
// With buffered channels, the send happens before the corresponding receive.
// The write to a happens before the send on c, which happens before the
// corresponding receive on c completes, which happens before the print.
func buffered() {
c := make(chan int, 10)
var a string
go func() {
a = "hello, world"
c <- 0
}()
<-c
// We are guaranteed to print "hello, world".
println(a)
}
// With both types of channels, a close happens before the corresponding receive.
// The write to a happens before the close on c, which happens before the
// corresponding receive on c completes, which happens before the print.
func closed() {
c := make(chan int, 10)
var a string
go func() {
a = "hello, world"
close(c)
}()
<-c
// We are guaranteed to print "hello, world".
println(a)
}