bugfix: Resolved a concurrency issue with ClientCounter. Previously, 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.

This commit is contained in:
GouJie
2024-01-20 00:17:15 +08:00
committed by finley
parent b63deb62bd
commit b7b8ece442
2 changed files with 38 additions and 2 deletions

View File

@@ -11,6 +11,7 @@ import (
"os"
"os/signal"
"sync"
"sync/atomic"
"syscall"
"time"
@@ -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 {
@@ -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)
}()