ws-examples
ws-examples copied to clipboard
Why we need mutex lock and unlock when reading conn
Hi @gobwas, thank you for creating awesome example ! I have a question about your sample code.
https://github.com/gobwas/ws-examples/blob/master/src/chat/chat.go#L79-L80
func (u *User) readRequest() (*Request, error) {
u.io.Lock()
defer u.io.Unlock()
...
}
Why we need lock when read ? if I put the Receive
(contain readRequest
) method in for-loop. (I am not using poller.Start(desc, func(ev netpoll.Event)
)
func (s *Socket) Start(conn net.Conn, name string) {
// Register incoming user in chat.
user := s.chat.Register(conn)
go func() {
retry := 0
defer conn.Close()
defer func() {
if r := recover(); r != nil {
log.Println(r)
}
}()
for {
err := user.Receive()
if err != nil {
// When receive failed, we can only disconnect broken
// connection and stop to receive events about it.
log.Printf("Read user [%s] - client [%s] text failed: %v\n", user.Name, name, err)
goto disconnect
}
log.Println("User receive successful")
disconnect:
if retry = retry + 1; retry > 3 {
log.Printf("Remove user [%s] - client [%s]\n", user.Name, name)
s.chat.Remove(user)
break
}
delay := time.Millisecond
log.Printf("Start receive error: %v; retrying in %s", err, delay)
time.Sleep(delay)
}
}()
}
===> its seem block write method such as
https://github.com/gobwas/ws-examples/blob/master/src/chat/chat.go#L135-L136
func (u *User) writeRaw(p []byte) error {
u.io.Lock()
defer u.io.Unlock()
...
}
because readRequest
have made u.io locked, and writeRaw
can not aquire this lock.
If I remove u.io.Lock()
in readRequest
method, Have it any problem?
Thank you !
https://golang.org/pkg/net/#Conn mention
Conn is a generic stream-oriented network connection.
Multiple goroutines may invoke methods on a Conn simultaneously.