Golang { Syntax int := 10 }

Golang Syntax _8


31. 셀렉트

package main
import "fmt"

func fibonacci(c, quit chan int) {
    var x, y int = 0, 1 
    for {
        select {
        case c <- x:
            x, y = y, x+y
        case <-quit:
            fmt.Println("quit")
            return
        }
    }
}

func main() {
    c := make(chan int)
    quit := make(chan int)
    go func() {
        for i := 0; i < 10; i++ {
            fmt.Println(<-c)
        }
        quit <- 0
    }()
    fibonacci(c, quit)
}
  • Go의 Select문은 고루틴이 다수의 통신 동작으로부터 수행 준비를 대기하게 해줌.
  • Select는 Case구문으로 받는 통신동작들 중 하나가 수행될 수 있을때 까지 대기함.
  • 다수의 채널이 동시에 준비되면 그 중 하나를 무작위로 선택함.

32. 셀렉트의 디폴트 케이스

package main
import (
    "fmt"
    "time"
)

func main() {
    tick := time.Tick(1e6)
    boom := time.After(5e8)
    for {
        select {
        case <-tick:
            fmt.Println("tick.")
        case <-boom:
            fmt.Println("BOOM!")
            return
        default:
            fmt.Println("    .")
            time.Sleep(5e7)
        }
    }
}
  • select의 default 케이스는 현재 준비가 완료된 케이스가 없을 때 수행된다.
  • 블록킹( 비동기적 ) 송/수신을 하고자 할때 default케이스를 사용할수 있다.

 

33. 연습문제

https://go-tour-kr.appspot.com/#69 참고

package main

import (
    "code.google.com/p/go-tour/tree"
	"fmt"
)

// Walk walks the tree t sending all values
// from the tree to the channel ch.
func Walk(t *tree.Tree, ch chan int) {
	_walk(t, ch)
	close(ch)
	
}

func _walk(t *tree.Tree, ch chan int) {
	if t != nil {
		_walk(t.Left, ch)
		ch <- t.Value
		_walk(t.Right, ch)
	}
}

// Same determines whether the trees
// t1 and t2 contain the same values.
func Same(t1, t2 *tree.Tree) bool {
	ch1 := make(chan int)
	ch2 := make(chan int)
	go Walk(t1, ch1)
	go Walk(t2, ch2)
	for i := range ch1 {
		if i != <- ch2 {
			return false
		}
	}
	return true	
}

func main() {
	//tree.New(2)
	ch := make(chan int)
	go Walk(tree.New(1), ch)
	for v := range ch {
		fmt.Print(v)
	}
	fmt.Println(Same(tree.New(1), tree.New(1)))
	fmt.Println(Same(tree.New(1), tree.New(2)))
}

 

글의 문제가 있다면 댓글을 달아 주세요.

이 사이트는 스팸을 줄이는 아키스밋을 사용합니다. 댓글이 어떻게 처리되는지 알아보십시오.