SoFunction
Updated on 2025-03-05

The usage of go language go func{select{}}

This article mainly introduces the usage of go language go func(){select{}}(), as follows:

go func(){
	select{
		......
	}
}()

It is an example of using Goroutine and Channel, and is also one of the hallmarks of asynchronous programming in Go language.
Specifically, this code creates an infinite loop, and then uses the select keyword to monitor any number of channels. Once one of them is ready, its corresponding code block will be executed.

This code pattern can help achieve efficient event loops, keep it efficient while handling multiple events at the same time and not stuck in the entire program. It is very suitable for use in scenarios such as high concurrency and network programming.

package main

import (
	"fmt"
	"time"
)

func main() {
	ch1 := make(chan string)
	ch2 := make(chan string)

	go func() {
		for {
			select {
			case msg1 := <-ch1:
				("Received message from ch1: ", msg1)
			case msg2 := <-ch2:
				("Received message from ch2: ", msg2)
			case <-( * 500):
				("Timed out!")
			}
		}
	}()

	ch1 <- "Message from channel-1"
	()
	ch2 <- "Message from channel-2"
	()
	ch1 <- "Another message from channel-1"
	( * 2)
}

Running results

Received message from ch1:  Message from channel-1
Timed out!
Received message from ch2:  Message from channel-2
Timed out!
Timed out!
Received message from ch1: Another message from channel-1
Timed out!
Timed out!
Timed out!

This is the end of this article about the usage of go language go func(){select{}}(). For more related go func(){select{}}(), please search for my previous articles or continue browsing the related articles below. I hope you will support me in the future!