# Go, select μ ν¨ν΄λ€
# select
select
λ switch
μ λΉμ·νμ§λ§ caseμ channel μ¬μ©ν¨.
# pattern - 1
package pattern1
func patter1() {
c1 := make(chan string)
c2 := make(chan string)
go func() {
for {
time.Sleep(5 * time.Second)
c1 <- "one"
}
}()
go func() {
for {
time.Sleep(10 * time.Second)
c2 <- "two"
}
}()
for {
fmt.Println("------------------start select------------------")
select {
case msg1 := <-c1:
fmt.Println("received", msg1)
case msg2 := <-c2:
fmt.Println("received", msg2)
}
fmt.Println("------------------end select-------------------")
}
}
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
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
case
μ μ±λμ κ°μ΄ λ€μ΄μ¬ λκΉμ§ select
λ¬Έμμ λΈλ‘λ¨.
# pattern - 2
package pattern
import (
"fmt"
"time"
)
func process(ch chan string) {
time.Sleep(10 * time.Second)
ch <- "process successful"
}
func scheduling() {
// do something
}
func pattern2() {
ch := make(chan string)
go process(ch)
for {
time.Sleep(1 * time.Second)
select {
case v := <-ch:
fmt.Println("received value: ", v)
return
default:
fmt.Println("no value received")
}
scheduling()
}
}
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
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
μ΄λ€ μμ°μκ° κ²°κ³Όλ₯Ό μ€ λ κΉμ§ κΈ°λ€λ¦¬λ λ°©μμ μ½λλ₯Ό ꡬμ±νλ ν¨ν΄.
# pattern - 3
package pattern
func sayHelloServer(ch chan string) {
ch <- "from server 1"
}
func sayHelloServer2(ch chan string) {
ch <- "from server 2"
}
func pattern3() {
output1 := make(chan string)
output2 := make(chan string)
go sayHelloServer(output1)
go sayHelloServer2(output2)
time.Sleep(1 * time.Second)
select {
case s1 := <-output1:
fmt.Println(s1)
case s2 := <-output2:
fmt.Println(s2)
}
}
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
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
# pattern - 4
package pattern
func consuming(scheduler chan string) {
select {
case <-scheduler:
fmt.Println("μ
λ ₯λ°μ.")
case <-time.After(5 * time.Second):
fmt.Println("νμμμ.") }
}
func producing(scheduler chan string) {
var name string
fmt.Print("> ")
fmt.Scanln(&name)
scheduler <- name
}
func pattern4() {
scheduler := make(chan string)
go consuming(scheduler)
go producing(scheduler)
time.Sleep(100 * time.Second)
}
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
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
μΆμ²: https://golangbot.com/select/