Wednesday, September 9, 2020

Golang: channels

 

package main
import "fmt"
func writeMessageToChannel(message chan string){
  message <- "Hello Uday!"
}
func main(){
  fmt.Println("Channel Demo")
  message := make(chan string)
  go writeMessageToChannel(message)//launches a separate goroutine to run parallelly
  fmt.Println("Greeting from the message channel: ",<-message)//will wait till channel sends the o/p
  close(message)//close channel
}

package main
import "fmt"
var done chan bool = make(chan bool)
func printGreetings(source string){
  for i:=0;i<9;i++{
   fmt.Println("Hello Uday!",i,source)
  }
  
  if source == "goroutine"{
    done <- true
  }
}
func main(){
  
  go printGreetings("goroutine")
  printGreetings("main function")
  
  <-done //this blocks the main function to wait till the done channel sends the o/p
}

Normal channels are synchronous, means both sending and receiving side will wait until the other side is ready.
Buffered channels are asynchronous, sending and receiving messages through the channel will not block unless the channel is full.
We can create a buffered channel using the built-in make function:
ch := make(chan type,capacity)
The difference from normal channel(capacity=1) syntax is we are passing the capacity with buffered channel.


package main
import "fmt"
var done chan bool = make(chan bool)

func main(){
 //we create a buffered channel of strings with a capacity of 3.
 //This means the channel buffer can hold up to 3 values
 messageQueue := make(chan string,3)
 messageQueue <- "one"
 messageQueue <- "two"
 messageQueue <- "three"
 //we drain the messageQueue by receiving all the values from the buffered channel
 fmt.Println(<-messageQueue)
 fmt.Println(<-messageQueue)
 fmt.Println(<-messageQueue)
}

Range over channels:
// An example of ranging over a channel.
//channelrange.go
package main

import "fmt"

func main() {

	// We create a buffered channel of strings with a capacity of 3
	// This means the channel buffer can hold up to 3 values
	messageQueue := make(chan string, 3)
	messageQueue <- "one"
	messageQueue <- "two"
	messageQueue <- "three"

	// Even though we close this non-empty channel, we can still receive
	// the remaining values (see below)
	close(messageQueue)

	// We use the range keyword to iterate over each element as it gets
	// received from the messageQueue.
	for m := range messageQueue {
		fmt.Println(m)
	}

}

// An example of sending and receiving a value through a channel.
//channeldemo.go
package main

import "fmt"

func writeMessageToChannel(message chan string) {

	message <- "Hello Gopher!"

}

func main() {

	fmt.Println("Channel Demo")

	message := make(chan string)
	go writeMessageToChannel(message)

	fmt.Println("Greeting from the message channel: ", <-message)

	close(message)
}

No comments:

Post a Comment