Introduction
Go is an open-source programming language aimed at being simple, reliable, and efficient. It is a compiled and statically typed general-purpose programming language with a simple syntax and extensive standard libraries. It has a select statement, which is similar to a switch statement. However, the case statement in the select statement refers to communication.
But do you know that we can handle deadlock conditions using the default case in the select statement?
This article will discuss the interesting concept of using the default case in select statements to handle deadlock. Let’s get started by discussing the basics of deadlock.
Select Statement in Go
The select statement is a fundamental conditional statement in Go programming. Like a switch statement in another programming language, the select statement allows us to choose or execute one expression out of many. The primary distinction between switch and select is that select operates on the wait principle, which will not run until the communication is complete. The term "communication" refers to sending and receiving data over any particular channel; once the communication is complete, the next check is performed, demonstrating that the select statement in the Go language is entirely dependent on the channel.
Let’s look at the syntax of the select statement given below.
select {
case send-channel-1 <- receive-channel-1:
//some expression for send-channel-1
case send-channel-2 <- receive-channel-2:
//some expression for send-channel-2
default:
//some expression for default
}
Select is a built-in statement in the Go programming language, and we don't need to import any packages to use it. We're passing the various send and receive statements after the select statement, which means each is a type of goroutine, and we know that goroutines work on the send and receive principle.
Example
In the below example, we have shown how to select one condition from numerous statements, allowing us to manage a variety of situations.
//Example of select statement
package main
import "fmt"
func main() {
c1 := make(chan string)
c2 := make(chan string)
//send
go func() {
c1 <- "one"
}()
go func() {
c2 <- "two"
}()
//receive
for i := 0; i < 2; i++ {
select {
case msg1 := <-c1:
fmt.Println("received", msg1)
case msg2 := <-c2:
fmt.Println("received", msg2)
default:
fmt.Println("no value received")
}
}
}
Output
We can see that we got the desired output of the above program, which prints the respective values returned by the functions.