ws-examples icon indicating copy to clipboard operation
ws-examples copied to clipboard

Why we need mutex lock and unlock when reading conn

Open euclid1990 opened this issue 5 years ago • 1 comments

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 !

euclid1990 avatar Jul 15 '19 09:07 euclid1990

https://golang.org/pkg/net/#Conn mention

Conn is a generic stream-oriented network connection.

Multiple goroutines may invoke methods on a Conn simultaneously.

euclid1990 avatar Jul 16 '19 09:07 euclid1990