BewareMyPower edited a comment on pull request #663:
URL: https://github.com/apache/pulsar-client-go/pull/663#issuecomment-963966453
> we agree that it really is necessary to call cond.Broadcast() after
cond.Wait()?
Yeah, I agree.
> If changeState gets called before waitUntilReady, then the broadcast
happens first and all is well.
>
> if waitUntilReady gets called before changeState, then waitUntilReady will
block on the cond.Wait(), whilst still holding the lock.
It makes sense. We should make the combination of `setState` and
`c.Broadcast()` an atomic operation.
> however you should avoid calling defer inside the for loop because a new
defer call will be pushed onto the stack for each loop invocation.
Thanks for pointing it out. I'm not so familiar with Go, just being used to
C++ object's lifetime rule, which is a little different.
----
The only question I'm still confused is, could you explain following code
and its output?
```go
package main
import (
"fmt"
"sync"
)
type connection struct {
sync.Mutex
cond *sync.Cond
}
func NewConnection() *connection {
cnx := &connection{}
cnx.cond = sync.NewCond(cnx)
return cnx
}
func main() {
cnx := NewConnection()
fmt.Printf("%v\n%v\n", cnx, cnx.cond.L)
cnx.cond.L.Lock()
cnx.Lock()
cnx.Unlock()
cnx.cond.L.Unlock()
}
```
```
&{{0 0} 0xc000104040}
&{{0 0} 0xc000104040}
fatal error: all goroutines are asleep - deadlock!
goroutine 1 [semacquire]:
sync.runtime_SemacquireMutex(0xc000010244, 0x0, 0x1)
/usr/local/go/src/runtime/sema.go:71 +0x47
sync.(*Mutex).lockSlow(0xc000010240)
/usr/local/go/src/sync/mutex.go:138 +0x105
sync.(*Mutex).Lock(...)
/usr/local/go/src/sync/mutex.go:81
main.main()
main.go:24 +0x175
```
It looks like `cnx.Lock()` and `cnx.cond.L.Lock()` are the same.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]