I have a recursive function that I will lock and mutate its internal state, however, it causes a deadlock. How can I implement such a recursive function without deadlock?
package main
import (
"fmt"
"sync"
)
type runner struct {
sync.Mutex
value int
}
func (r *runner) decrement() {
r.Lock()
defer r.Unlock()
if r.value == 0 {
return
}
r.value--
r.decrement()
}
func main() {
r := runner{
value: 10,
}
r.decrement()
fmt.Printf("r: %v\n", r.value)
}
Expect running the above code would print r: 0
, but actually got deadlock:
fatal error: all goroutines are asleep - deadlock!