Golang Select Multiple Channels

Golang Select multiple Channels

In the previous blog, we learned about the Golang channel, deadlock, buffered channels. This time we will take a look at Select Statement for Channels in Golang. The Select Statement helps us to select multiple channels in Golang.

Click here to read about Golang Channel and Deadlock.

Select Multiple Channels

Many times we pass two or more kinds of data, like if we have to pass a Video that contains video as well as audio data. The sending of data may differ and thus we will have to select that particular channel separately.

Select Statement is like Switch statement in Golang.

Example:

package main

import (
	"fmt"
	"time"
)

func video(ch1 chan string) {
	time.Sleep(time.Second * 1)
	ch1 <- "Video Data"
}
func audio(ch2 chan string) {
	time.Sleep(time.Second * 2)
	ch2 <- "Audio Data"
}

func main() {

	ch1 := make(chan string)
	ch2 := make(chan string)

	go video(ch1)
	go audio(ch2)

	for i := 0; i < 2; i++ {

		select {
		case video := <-ch1:
			fmt.Println(video)
		case audio := <-ch2:
			fmt.Println(audio)
		}
	}

	
}

Output:

After 2 seconds

Video Data

1 second after Video Data is Printed.

Audio Data

And we have successfully separated both the channel values using Golang select Statement.

Golang Signal Only Channel Example

package main

import (
	"fmt"
	"time"
)

type data struct {
	audio string
	video string
}

var d = make(chan data, 50)
var soc = make(chan struct{}, 50)

func display() {
	for {
		select {
		case data := <-d:
			fmt.Println(data)
		case <-soc:
			break
		}
	}
}

func main() {

	go display()

	d <- data{"Audio Data 1", "Video Data 1"}
	d <- data{"Audio Data 2", "Video Data 2"}
	soc <- struct{}{}
	time.Sleep(100 * time.Millisecond)

}
{Audio Data 1 Video Data 1}
{Audio Data 2 Video Data 2}

When the signal only channel is received we exit out of the loop.

Hope you like it!

Learn more about Channels in Golang from the official Documentation.

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *