Here's some code I've been playing with:
package main
import "fmt"
func main() {
channel := make(chan int)
flag := false
go func() {
for {
channel <- 1
}
}()
for {
select {
case <-channel:
fmt.Println(flag)
if !flag {
flag = true
break
}
fmt.Println(flag)
}
}
}
I would expect at least one false
in there but when I execute the code I only get true
s. Can someone explain why please?
I'm sure it has something to do with locks but when I try to wrap the case
content around a lock I get a false
(finally!) but then fatal error: all goroutines are asleep - deadlock!
:
for {
select {
case <-channel:
mutex.Lock()
fmt.Println(flag)
if !flag {
flag = true
break
}
fmt.Println(flag)
mutex.Unlock()
default:
// no communication
}
}
There's no reason to warp flag
with a Mutex since the code around it is not concurrent.
you can check your code here https://play.golang.org/p/OJue5lcIZlw it does print the first false
.
as for why you're getting that error as leaf bebop said because your breaking the code you run into a deadlock for trying to lock on a locked mutex.
you could use defer mutex.Unlock()
or unlock before break
to solve that.