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

huangapple go评论77阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2014年9月25日 23:01:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/26041849.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定