Confused about blocking channels - go

I have this block of code that is supposed to wait 10 seconds before the program exits, but it only works if I add some sort of print something for it afterwards. Why is that? I want it to wait 10 seconds without having to uncomment that print statement.
func main() {
forever := make(chan bool)
go func() {
fmt.Println("why")
time.Sleep(10*time.Second)
//fmt.Println("here")
forever <- false
}()
fmt.Println("forever")
<- forever
}
This also works:
func main() {
forever := make(chan bool)
go func() {
fmt.Println("why")
time.Sleep(10*time.Second)
forever <- false
}()
fmt.Println(<- forever)
}
The following program does not wait for 10 seconds when it is run in Go playground:
package main
import (
"time"
)
func main() {
forever := make(chan bool)
go func() {
time.Sleep(10 * time.Second)
forever <- false
}()
<-forever
}

Technically, it's a "feature" of the playground. When everything is blocked waiting on time in the playground, time will artificially advance until things unblock... or it decides things really are deadlocked. See "Faking Time" section in the Golang Playground article.

Related

How can one close a channel in a defer block safely?

Consider the following example:
package main
import (
"fmt"
"time"
)
func main() {
ticker := time.NewTicker(2 * time.Second)
done := make(chan bool)
defer func() {
fmt.Println("exiting..")
done <- true
close(done)
}()
go func(ticker *time.Ticker, done chan bool) {
for {
select {
case <-done:
fmt.Println("DONE!")
break
case <-ticker.C:
fmt.Println("TICK!...")
}
}
}(ticker, done)
time.Sleep(7 * time.Second)
}
The goroutine waiting to receive from done never receives as (I am guessing) the main goroutine finished beforehand. However if I change the sleep time of the main goroutine to 8 seconds it receives a message; Why is there this dependency on the sleep time?
Is it because there is that second difference that keeps the goroutine alive and the there isn't enough time to kill it?
How would I than kill the goroutine gracefully?
You need to ensure that main does not return before the goroutine finishes.
The simplest way to do this is using a WaitGroup:
var wg sync.WaitGroup
defer wg.Wait()
wg.Add(1)
go func() {
defer wg.Done()
// …
Note that defers run in reverse order, so you must put defer wg.Wait() before defer close(done), otherwise it will deadlock.

How to make this golang for-select code work?

Question
How to make the below code print "QUIT" after 3 seconds?
Code
package main
import (
"fmt"
"time"
)
func main() {
quit := make(chan struct{})
tasks := make(chan struct{})
go func(){
time.Sleep(1 * time.Second)
tasks <- struct{}{}
}()
go func(){
time.Sleep(3 * time.Second)
quit <- struct{}{}
}()
for {
select {
case <-quit:
fmt.Println("QUIT")
return
case <-tasks:
fmt.Println("Doing")
// do some long time jobs more than 10 seconds
time.Sleep(10 * time.Second)
}
}
}
Observations
The above code prints "Doing". and sleep 10 seconds, then print "QUIT".
How to interrupt this sleep, let it receive quit channel after 3 seconds and print "QUIT"?
It seems select is blocked by case tasks, and it will not receive from the quit channel after 3 seconds.
To signal end of an asynchronous task it is a best practice to close the channel, this is rather important to prevent many missuse that leads to various deadlocks.
In your original code I would have written close(quite) rather than quit <- struct{}{}
Remember, read on a closed does not block and always return the zero value, that is the trick.
Anyways, appart from this, an elegant way to solve your problem is to use a combination of both context.Context and time.After.
time.After will help you block on a selectable task set.
context.Context is better suited to handle this kind of signals.
https://play.golang.org/p/ZVsZw3P-YHd
package main
import (
"context"
"log"
"time"
)
func main() {
log.Println("start")
defer log.Println("end")
ctx, cancel := context.WithCancel(context.Background())
tasks := make(chan struct{})
go func() {
time.Sleep(1 * time.Second) // a job
tasks <- struct{}{}
}()
go func() {
time.Sleep(3 * time.Second) // a job
cancel()
}()
for {
select {
case <-ctx.Done():
log.Println("QUIT")
return
case <-tasks:
log.Println("Doing")
// do some long time jobs more than 10 seconds
select {
case <-ctx.Done():
return
case <-time.After(time.Second * 10):
}
}
}
}
The second job is running for 10 seconds, so it will block the loop for that time, and the signal you sent into the quit channel will not be received until this job is complete.
To interrupt the time-consuming job, maybe you can split it into another goroutine. Something like this would do:
go func() {
for {
select {
case <-tasks:
fmt.Println("Doing")
// do some long time jobs more than 10 seconds
time.Sleep(10 * time.Second)
}
}
}()
<-quit
fmt.Println("QUIT")
It would be easier to use [sync.WaitGroup.
package main
import (
"fmt"
"sync"
"time"
)
func worker(msg string, duration time.Duration, doing bool, wg *sync.WaitGroup) {
defer wg.Done()
time.Sleep(duration)
fmt.Println(msg)
if doing {
time.Sleep(10 * time.Second)
}
}
func main() {
var wg sync.WaitGroup
msgs := [2]string{"QUIT", "Doing"}
durations := [2]time.Duration{3 * time.Second, 1 * time.Second}
doing := [2]bool{false, true}
for i, msg := range msgs {
wg.Add(1)
go worker(msg, durations[i], doing[i], &wg)
}
wg.Wait()
}

Go channel deadlock is not happening

package main
import (
"fmt"
"time"
)
func main() {
c := make(chan int)
go func() {
fmt.Println("hello")
c <- 10
}()
time.Sleep(2 * time.Second)
}
In the above program, I have created a Go routine which is writing to channel c but there is no other go routine which is reading from the channel. Why isnt there a deadlock in this case?
A deadlock implies all goroutines being blocked, not just one arbitrary goroutine of your choosing.
The main goroutine is simply in a sleep, once that is over, it can continue to run.
If you switch the sleep with a select{} blocking forever operation, you'll get your deadlock:
c := make(chan int)
go func() {
fmt.Println("hello")
c <- 10
}()
select {}
Try it on the Go Playground.
See related: Why there is no error that receiver is blocked?

why I can not see output when received value by channel

in the next example, I don't understand why end value not printed when received
package main
import "fmt"
func main() {
start := make(chan int)
end := make(chan int)
go func() {
fmt.Println("Start")
fmt.Println(<-start)
}()
go func() {
fmt.Println("End")
fmt.Println(<-end)
}()
start <- 1
end <- 2
}
I know sync.WaitGroup can solve this problem.
Because the program exits when it reaches the end of func main, regardless of whether any other goroutines are running. As soon as the second function receives from the end channel, main's send on that channel is unblocked and the program finishes, before the received value gets a chance to be passed to Println.
The end value is not printed because as soon as the main goroutine (the main function is actually a goroutine) is finished (in other terms get unblocked) the other non-main goroutines does not have the chance to get completed.
When the function main() returns, the program exits. Moreover goroutines are independent units of execution and when a number of them starts one after the other you cannot depend on when a goroutine will actually be started. The logic of your code must be independent of the order in which goroutines are invoked.
One way to solve your problem (and the easiest one in your case) is to put a time.Sleep at the end of your main() function.
time.Sleep(1e9)
This will guarantee that the main goroutine will not unblock and the other goroutines will have a change to get executed.
package main
import (
"fmt"
"time"
)
func main() {
start := make(chan int)
end := make(chan int)
go func() {
fmt.Println("Start")
fmt.Println(<-start)
}()
go func() {
fmt.Println("End")
fmt.Println(<-end)
}()
start <- 1
end <- 2
time.Sleep(1e9)
}
Another solution as you mentioned is to use waitgroup.
Apart from sleep where you have to specify the time, you can use waitgroup to make you program wait until the goroutine completes execution.
package main
import "fmt"
import "sync"
var wg sync.WaitGroup
func main() {
start := make(chan int)
end := make(chan int)
wg.Add(2)
go func() {
defer wg.Done()
fmt.Println("Start")
fmt.Println(<-start)
}()
go func() {
defer wg.Done()
fmt.Println("End")
fmt.Println(<-end)
}()
start <- 1
end <- 2
wg.Wait()
}

why does it seem that sleep doesn't work in goroutine

package main
import (
"fmt"
"time"
)
func main() {
c := make(chan struct{})
count := 1
go func() {
for {
fmt.Println("foo", count)
count++
time.Sleep(2)
}
c <- struct{}{}
}()
fmt.Println("Hello World!")
<-c
}
This is my code , and I found it didn't sleep 2 every loop, and printed quickly. What's the reason of it? What I searched is that sleep will make goroutine give up control of cpu and when it get the control again will it check itself is sleeping?
time.Sleep takes its Duration in nanoseconds, so to delay 2 seconds it should be;
time.Sleep(2000000000)
or, as #Ainar-G points out in the comments, the more readable;
time.Sleep(2 * time.Second)

Resources