Skip to content

Commit

Permalink
added mutex for solve race condition in server
Browse files Browse the repository at this point in the history
  • Loading branch information
stanipetrosyan committed Jun 7, 2024
1 parent bedd743 commit 852d2cb
Showing 1 changed file with 6 additions and 0 deletions.
6 changes: 6 additions & 0 deletions server.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"encoding/json"
"fmt"
"net"
"sync"
)

type Server interface {
Expand All @@ -12,6 +13,7 @@ type Server interface {
}

type tcpServer struct {
sync.RWMutex
address string
clients []net.Conn
}
Expand All @@ -32,12 +34,15 @@ func (s *tcpServer) Listen() (Server, error) {
continue
}

s.Lock()
s.clients = append(s.clients, conn)
s.Unlock()
}
}

func (s *tcpServer) Publish(channel string, message Message) {
var encoder *json.Encoder
s.Lock()
for _, client := range s.clients {
encoder = json.NewEncoder(client)
err := encoder.Encode(Request{Channel: channel, Message: message})
Expand All @@ -46,6 +51,7 @@ func (s *tcpServer) Publish(channel string, message Message) {
fmt.Println("Error:", err)
}
}
s.Unlock()
}

func NewServer(address string) Server {
Expand Down

0 comments on commit 852d2cb

Please sign in to comment.