Sobes.tech
Middle+

```go import ( "fmt" "runtime" "time" ) func main() { runtime.GOMAXPROCS(2) var c chan int for i := 0; i < 5; i++ { go sleeping(i, c) } for i := 0; i < 5; i++ { gopherID := <-c fmt.Println("routine ", gopherID, " has finished sleeping") } } func sleeping(id int, c chan int) { time.Sleep(3 * time.Second) fmt.Println("... ", id, " time to stop ...") c <- id } ```

sobes.tech AI

Answer from AI

This example creates 5 goroutines, each of which sleeps for 3 seconds, then sends its identifier to the channel c.

However, the channel c is declared but not initialized, which will cause a panic when attempting to write to it. To fix this, you need to initialize the channel, for example:

c := make(chan int)

Also, runtime.GOMAXPROCS(2) limits the number of OS threads used to 2, which affects parallelism.

After starting the goroutines, the main thread reads from the channel 5 times, which guarantees waiting for all goroutines to finish.

Fixed code snippet:

func main() {
	runtime.GOMAXPROCS(2)
	c := make(chan int)
	for i := 0; i < 5; i++ {
		go sleeping(i, c)
	}
	for i := 0; i < 5; i++ {
		gopherID := <-c
		fmt.Println("routine", gopherID, "has finished sleeping")
	}
}
```go import ( "fmt" "runtime" "time" ) func main() {… - sobes.tech