Go course

ChannelsSelect

Go

Display

Theme

Channels · Test exercise

Select

select looks like switch, but every case is a channel operation. select waits until one of the cases can run, then runs that case:

select {
case pesan := <-chatGrup:
	fmt.Println("grup:", pesan)
case pesan := <-chatPribadi:
	fmt.Println("pribadi:", pesan)
}

If several cases are ready at the same time, Go picks one of them at random. Don't rely on the order you wrote the cases in.

default: non-blocking operations

With default, select never waits. If no case is ready, default runs right away:

select {
case antrean <- pesanan:
	fmt.Println("pesanan masuk antrean")
default:
	fmt.Println("antrean penuh, coba lagi nanti")
}

This pattern is handy for "try to send" or "try to receive" without leaving a goroutine stuck.

Timeouts

time.After(d) returns a channel that receives a single value after duration d. Combine it with select and you get a timeout:

select {
case hasil := <-unduhan:
	fmt.Println("selesai:", hasil)
case <-time.After(3 * time.Second):
	fmt.Println("waktu habis")
}

Merging several channels

To read from two channels until both are closed, use comma-ok to detect when one closes, then set that channel variable to nil. Receiving from a nil channel always blocks, so that case is effectively "switched off" and select only pays attention to the channels that are still open:

for a != nil || b != nil {
	select {
	case v, ok := <-a:
		if !ok {
			a = nil
			continue
		}
		fmt.Println("dari a:", v)
	case v, ok := <-b:
		if !ok {
			b = nil
			continue
		}
		fmt.Println("dari b:", v)
	}
}

Function parameters are local variables, so setting one to nil doesn't affect the caller's channel.

Task

Complete three functions for a multiplayer game server:

  1. cobaKirim(ch chan<- string, pesan string) bool tries to send pesan without blocking. Return true if it was sent, or false if the channel is currently full.
  2. cobaTerima(ch <-chan string) (string, bool) tries to receive without blocking. Return (nilai, true) if a value is available, or ("", false) if no value is ready or the channel is closed.
  3. gabungSkor(timMerah, timBiru <-chan int) int receives scores from both channels until both are closed, then returns the total of all the scores.
main.go
package main

import "fmt"

func cobaKirim(ch chan<- string, pesan string) bool {
	// TODO: select dengan case kirim dan default
	return false
}

func cobaTerima(ch <-chan string) (string, bool) {
	// TODO: select dengan case terima (comma-ok) dan default
	return "", false
}

func gabungSkor(timMerah, timBiru <-chan int) int {
	// TODO: select dalam loop sampai kedua channel ditutup (trik channel nil)
	return 0
}

func main() {
	lobi := make(chan string, 1)
	fmt.Println(cobaKirim(lobi, "pemain1 masuk"))
	fmt.Println(cobaKirim(lobi, "pemain2 masuk"))
	fmt.Println(cobaTerima(lobi))
	fmt.Println(cobaTerima(lobi))

	merah, biru := make(chan int), make(chan int)
	go func() {
		for _, s := range []int{10, 20} {
			merah <- s
		}
		close(merah)
	}()
	go func() {
		for _, s := range []int{5, 5, 5} {
			biru <- s
		}
		close(biru)
	}()
	fmt.Println("Total skor:", gabungSkor(merah, biru))
}

Output

Go runtime not loaded yet

Press Run to see the output, or Submit to check your code.

Ctrl/Cmd + Enter: Run · Ctrl/Cmd + Shift + Enter: Submit · Ctrl/Cmd + S: tidy the code (gofmt)