log.Flags()是否应该与write共享相同的sync.Mutex?

问题描述:

I have the following code:

package main

import(
    "log"
    "os"
)

type LogFilter struct {}

func (t *LogFilter) Write(p []byte) (int, error) {
    _ = log.Flags()
    return os.Stderr.Write(p)
}

func main() {
    log.SetOutput(&LogFilter{})
    log.Println("Hello, playground")
}

Which Deadlocks because of http://golang.org/src/pkg/log/log.go line 135 defers the lock until after the write. Which in the write I'm calling Flags which tried to get the lock.

Is there any reason that they (Write & Flags) should share the same mutex?

It shares the mutex, because the Logger also reads its internal flags field when writing output.

Granted it could be more granularly locked, but you'd have to make a good case to justify the added complication. If you need the flags in your filter, I would copy them in when you initialize your structure.