Wrote this very basic code to understand channels.
If there is a wait in a goroutine, why is the main goroutine waiting on it? I read that the main goroutine needs to have a wait time as the control is passed back to it immediately after invoking goroutine.
Why are goroutines not designed like main thread and child threads in java where they can run in parallel?
func main() {
channel := make(chan int)
go func() {
time.Sleep(3*time.Second)
}()
for {
fmt.Println("../");
<-channel
}
}
I think your main thread is waiting for something to come from the channel
func main() {
channel := make(chan int)
go func() {
time.Sleep(3*time.Second)
channel <- 1 // Sending something to the channel to let the main thread continue
channel <- 2
}()
for {
fmt.Println("../");
<-channel // Waiting for something to come from the channel
}
}
regarding your specific questions:
If there is a wait in a goroutine, why is the main goroutine waiting on it?
It doesn't wait for it, it probably waiting on the channel.
I read that the main goroutine needs to have a wait time as the control is passed back to it immediately after invoking goroutine.
If your main wasn't waiting on the channel (or stack in an endless loop) it had finished and closed the application. GoRoutines closes with the main thread (like Java daemon threads)
Why are goroutines not designed like main thread and child threads in java where they can run in parallel?
They actually do (: