为什么在日志包中没有使用锁来进行同步?

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

why didn't use lock to sync in log package

问题

SetOutput方法使用mu来进行锁定,而SetFlags方法没有使用mu进行锁定。这是因为它们对共享数据的访问方式不同。

SetOutput方法中,通过使用std.mu.Lock()std.mu.Unlock()来锁定和解锁std结构体中的互斥锁mu。这是因为在设置输出目标时,可能会涉及到对共享数据的修改操作,需要确保在多个goroutine同时访问时的数据一致性和线程安全性。

而在SetFlags方法中,没有对mu进行锁定。这是因为设置输出标志位时,并不涉及对共享数据的修改操作,只是简单地返回或设置标志位的值。因此,不需要使用互斥锁来保护对共享数据的访问。

通过这种方式,可以根据具体的操作需求来选择是否使用互斥锁来保护共享数据的访问。

英文:

I'm reading log source code,I'm confused in here:

// SetOutput sets the output destination for the standard logger.
func SetOutput(w io.Writer) {
	std.mu.Lock()
	defer std.mu.Unlock()
	std.out = w
}
  
// Flags returns the output flags for the standard logger.
func Flags() int {
	return std.Flags()
}
  
// SetFlags sets the output flags for the standard logger.
func SetFlags(flag int) {
	std.SetFlags(flag)
}

why SetOutPut use mu to lock but SetFlags don't use mu to lock?

答案1

得分: 3

SetOutput正在修改std默认日志记录器的内部状态。

log.SetFlagsstd上调用SetFlags,它已经锁定了日志记录器本身。

英文:

SetOutput is altering the internal state of the std default Logger.

log.SetFlags is calling SetFlags on std, which already locks the logger itself.

huangapple
  • 本文由 发表于 2016年1月21日 00:04:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/34904822.html
匿名

发表评论

匿名网友

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

确定