09/02 Study Daily record

손진성·2022년 2월 9일
0

Go Channels

  • A way for goroutines to communicate
  • A channel passes a value from one goroutine to another
  • "Share memory by communicating"
  • Create a channel => ch := make(chan )
  • Send value of variable X through a channel => ch <- X,,, goroutine will wait till another goroutine receives the value
  • Receive the value on the other end of a channel => V:= <-ch, goroutine will wait until there is a value waiting inside ch
func main() {
	c:= make(chan bool)
	go waitAndSay(c, "world")
	fmt.Println("Hello")

	//we send a signal to c in order to allow waitAndSay to continue
	c<- true

	//we wait to receive another signal on c before we exit
	<-c
}

func waitAndSay(c chan bool, s string) {
	if b := <-c; b {
		fmt.Println(s)
	}
	c <- true
}

Buffered Channels

  • Can be considered as a buffer of stacked channels
  • To declare a buffered channel => ch := make(chan<type>, <number of buffered channels>), example => ch:= make(chan int, 100)
  • Senders only block when the buffer is full
  • Receivers block when the buffer is empty

Code

func main() {
	ch := make(chan string, 2)

	ch <- "Hello"
	ch <- "World"

	fmt.Println(<-ch)
	fmt.Println(<-ch)
}

Result

Hello
World

Code

func main() {
	ch := make(chan string, 2)

	ch <- "Hello"
	ch <- "World"
  	ch <- "Hello again"

	fmt.Println(<-ch)
	fmt.Println(<-ch)
}

Result

fatal error: all goroutines are asleep - deadlock!

goroutine 1 [chan send]:
main.main()
        C:/Users/7205033/Documents/Go/Learngo/Udemy/gochannel/main.go:50 +0x5c
exit status 2

Range and Close

  • Range can be used to receive values from a channel inside a for loop
  • Close is used to indicate the channel has retired

Code

func main() {
	c := make(chan string)
	go SayHelloMultipleTimes(c, 5)
	for s := range c {
		fmt.Println(s)
	}

	v, ok := <-c
	fmt.Println("Channel close?", !ok, " value ", v)
}

func SayHelloMultipleTimes(c chan string, n int) {
	for i := 0; i <= n; i++ {
		c <- "Hello"
	}
	close(c)
}

Result

Hello
Hello
Hello
Hello
Hello
Hello
Channel close? true  value

-Likewise, when data is received, if there is no data transmitted and data is received from the channel, it enters the infinite standby state. However, if you close the channel after sending data to the channel at this time, you can no longer transmit data to the corresponding channel, but you can continue to receive after the channel is closed. To close a channel, use the "close(channelname)" format.

profile
Gopyther

0개의 댓글