英文:
Should log.Flags() share the same sync.Mutex as write?
问题
我有以下代码:
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")
}
由于http://golang.org/src/pkg/log/log.go的第135行将锁推迟到写操作之后,导致死锁。在写操作中,我调用了Flags函数,该函数尝试获取锁。
它们(Write和Flags)是否应该共享同一个互斥锁?
英文:
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?
答案1
得分: 0
它共享互斥锁,因为Logger
在写入输出时也会读取其内部的flags
字段。
虽然可以更细粒度地进行锁定,但你必须提出充分的理由来证明增加的复杂性是合理的。如果你的过滤器需要使用这些标志,我建议在初始化结构时将它们复制进去。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论