# 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

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

μ–΄λ–€ μƒμ‚°μžκ°€ κ²°κ³Όλ₯Ό 쀄 λ•Œ κΉŒμ§€ κΈ°λ‹€λ¦¬λŠ” λ°©μ‹μ˜ μ½”λ“œλ₯Ό κ΅¬μ„±ν•˜λŠ” νŒ¨ν„΄.

# 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

# 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

좜처: https://golangbot.com/select/