Skip to content

Commit

Permalink
bugfix: Resolved a concurrency issue with ClientCounter. Previously, …
Browse files Browse the repository at this point in the history
…directly decrementing ClientCounter in multiple goroutines (ClientCounter--) could lead to data races and inconsistencies. Now, by using atomic.AddInt32(&ClientCounter, -1), we ensure safe updates to the counter, maintaining its accuracy and stability even in high concurrency scenarios.
  • Loading branch information
gou-jjjj committed Jan 19, 2024
1 parent 9e21880 commit f21658e
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 2 deletions.
37 changes: 37 additions & 0 deletions tcp/echo_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,3 +51,40 @@ func TestListenAndServe(t *testing.T) {
closeChan <- struct{}{}
time.Sleep(time.Second)
}

func TestClientCounter(t *testing.T) {
const addr = "127.0.0.1:8080"
go func() {
err := ListenAndServeWithSignal(&Config{
Address: addr,
MaxConnect: 10000,
Timeout: 1 * time.Second,
}, MakeEchoHandler())
if err != nil {
t.Errorf("listen and serve error: %s", err.Error())
}
}()

sleepUntil := time.Now().Add(3 * time.Second)
subtime := func() time.Duration {
return sleepUntil.Sub(time.Now())
}

for i := 0; i < 1000; i++ {
go func() {
conn, err := net.Dial("tcp", addr)
if err != nil {
t.Errorf(err.Error())
}
defer conn.Close()

time.Sleep(subtime())
}()
time.Sleep(5 * time.Microsecond)
}

time.Sleep(3 * time.Second)
if ClientCounter != 0 {
t.Errorf("client counter error: %d", ClientCounter)
}
}
5 changes: 3 additions & 2 deletions tcp/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import (
"os"
"os/signal"
"sync"
"sync/atomic"
"syscall"
"time"

Expand All @@ -26,7 +27,7 @@ type Config struct {
}

// ClientCounter Record the number of clients in the current Godis server
var ClientCounter int
var ClientCounter int32

// ListenAndServeWithSignal binds port and handle requests, blocking until receive stop signal
func ListenAndServeWithSignal(cfg *Config, handler tcp.Handler) error {
Expand Down Expand Up @@ -88,7 +89,7 @@ func ListenAndServe(listener net.Listener, handler tcp.Handler, closeChan <-chan
go func() {
defer func() {
waitDone.Done()
ClientCounter--
atomic.AddInt32(&ClientCounter, -1)
}()
handler.Handle(ctx, conn)
}()
Expand Down

0 comments on commit f21658e

Please sign in to comment.