An interview question about goroutine

problem

package main

import (
 "fmt"
 "time"
)

func main() {
    
    
 ch1 := make(chan int)
 go fmt.Println(<-ch1)
 ch1 <- 5
 time.Sleep(1 * time.Second)
}

Q:
What does the above code output?

Is it 5 or something else?

analysis

If the code is replaced as follows:

package main

import (
 "fmt"
 "time"
)

func main() {
    
    
 ch1 := make(chan int)
  go func(){
    
    
    fmt.Println(<-ch1)
  }()
 ch1 <- 5
 time.Sleep(1 * time.Second)
}

Answer: The
above problem is causing deadlock.
The second case is normal output 5.

It is explained here that the parameters of the function call after the go statement will be evaluated first, which is the same as the evaluation of a normal function call.
This means that the actual parameters are evaluated before the function is called.

Therefore, in this question, the <-ch1 in the go fmt.Println(<-ch1) statement is evaluated in the main goroutine. This is equivalent to an unbuffered chan. Both sending and receiving operations are performed in a goroutine (main goroutine), thus causing a deadlock.

Further, you can see the difference between the above two methods through compilation.

Expand

In addition, pay attention to the defer statement. For example, the following approach is incorrect:

defer recover()

Instead, use this method:

 defer func() {
    
    
  if v := recover(); v != nil {
    
    
   _ = fmt.Errorf("PANIC=%v", v)
  }
 }()

Guess you like

Origin blog.csdn.net/csdniter/article/details/112968783