From 101927e343b545f5282e9e8e1fdc73a3b59341ff Mon Sep 17 00:00:00 2001 From: Max Date: Mon, 24 Feb 2025 17:24:34 +0800 Subject: [PATCH] Add thread-safe write method with mutex synchronization - Introduce sync.Mutex to protect concurrent writes to response writer - Add locking mechanism in Write method to prevent race conditions - Ensure safe and synchronized message writing in multi-threaded contexts --- neo/message/message.go | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/neo/message/message.go b/neo/message/message.go index 02341acd..09832edc 100644 --- a/neo/message/message.go +++ b/neo/message/message.go @@ -4,6 +4,7 @@ import ( "fmt" "os" "strings" + "sync" "github.com/fatih/color" "github.com/gin-gonic/gin" @@ -15,6 +16,8 @@ import ( "github.com/yaoapp/yao/openai" ) +var locker = sync.Mutex{} + // Message the message type Message struct { ID string `json:"id,omitempty"` // id for the message @@ -721,6 +724,11 @@ func (m *Message) Callback(fn interface{}) *Message { // Write writes the message to response writer func (m *Message) Write(w gin.ResponseWriter) bool { + + // Sync write to response writer + locker.Lock() + defer locker.Unlock() + defer func() { if r := recover(); r != nil {