Golang日志中如何解决并发写入问题

作者:袖梨 2026-07-20

在Golang中,处理并发写入日志的问题可以通过使用sync.Mutex或者sync.RWMutex来实现。这两种方法都可以确保在同一时间只有一个goroutine能够访问和修改日志数据,从而避免数据竞争和不一致的问题。

Golang日志中如何处理并发写入问题

以下是使用sync.Mutex和sync.RWMutex处理并发写入日志问题的示例:

  1. 使用sync.Mutex:
package mainimport ("fmt""log""os""sync""time")type Logger struct {musync.Mutexlogger *log.Logger}func NewLogger() *Logger {return &Logger{logger: log.New(os.Stdout, "", log.LstdFlags),}}func (l *Logger) Log(message string) {l.mu.Lock()defer l.mu.Unlock()l.logger.Println(message)}func main() {logger := NewLogger()for i := 0; i < 10; i++ {go func(i int) {logger.Log(fmt.Sprintf("Log message %d from goroutine %d", i, i))}(i)}time.Sleep(1 * time.Second)}
  1. 使用sync.RWMutex:
package mainimport ("fmt""log""os""sync""time")type Logger struct {musync.RWMutexlogger *log.Logger}func NewLogger() *Logger {return &Logger{logger: log.New(os.Stdout, "", log.LstdFlags),}}func (l *Logger) Log(message string) {l.mu.Lock()defer l.mu.Unlock()l.logger.Println(message)}func (l *Logger) ReadLog() string {l.mu.RLock()defer l.mu.RUnlock()buf := make([]byte, 1024)n, _ := l.logger.Out.Write(buf)return string(buf[:n])}func main() {logger := NewLogger()for i := 0; i < 10; i++ {go func(i int) {logger.Log(fmt.Sprintf("Log message %d from goroutine %d", i, i))}(i)}time.Sleep(1 * time.Second)fmt.Println(logger.ReadLog())}

在这两个示例中,我们创建了一个自定义的Logger结构体,其中包含一个sync.Mutex或sync.RWMutex和一个log.Logger。我们在Log方法中使用Lock和Unlock方法来确保在同一时间只有一个goroutine能够访问和修改日志数据。在第二个示例中,我们还添加了一个ReadLog方法,它使用RLock和RUnlock方法来允许多个goroutine同时读取日志数据。

相关文章

精彩推荐