用于防止伪共享的奇怪代码

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

Strange code for preventing false sharing

问题

我想讨论一下来自这个链接的Golang中的以下结构:

// Local per-P Pool appendix.
type poolLocal struct {
	private interface{}   // 仅由相应的P使用。
	shared  []interface{} // 任何P都可以使用。
	Mutex                 // 保护shared。
	pad     [128]byte     // 防止伪共享。
}

上述结构只能一次由一个线程访问,因为使用了Mutex。编码器会在线程开始时锁定该结构,在线程完成时解锁它。因此,内存在线程之间不共享。因此,不会有多个核心访问内存。根据我的理解,这里不会发生伪共享。如果伪共享不会发生,为什么编码器要用额外的字节(pad [128]byte)填充结构?我的理解错了吗?

英文:

I want to discuss the following structure in golang from this link

// Local per-P Pool appendix.
    57	type poolLocal struct {
    58		private interface{}   // Can be used only by the respective P.
    59		shared  []interface{} // Can be used by any P.
    60		Mutex                 // Protects shared.
    61		pad     [128]byte     // Prevents false sharing.
    62	}

The above structure can be accessed only one thread at a time as Mutex is used. The coder will Lock the structure in the beginning of a thread and unlock it when the thread completes. So the memory is not shared between threads. So no more than one core will have
access to the memory
. So, by my understanding, false sharing cannot happen here. If false sharing cannot happen, why did the coder pad the structure
with extra bytes (pad [128]byte) ? Is my understanding wrong?

答案1

得分: 2

在同一缓存行上的内存位置会受到伪共享的影响,这对性能非常不利。缓存行的大小范围从32到128字节不等,具体取决于处理器型号。使用128字节的填充可以减少不同进程使用相同缓存行的机会,从而提高性能。

根据我的理解,以下代码可能更好,因为它更明确:

type poolLocal struct {
      _       [64]byte         // 防止伪共享。
      private interface{}       // 只能由相应的 P 使用。
      shared  []interface{}     // 可由任何 P 使用。
      Mutex                     // 保护 shared。
      _       [64]byte         // 防止伪共享。
}
英文:

Memory locations on the same cache line are subject to false-sharing, which is very bad for performance.
Cache line size ranges from 32 to 128 bytes, depending on processor model. 128 byte pad will reduce chance for same cache line being used by different processes and that improvesthe performace

as i see it, the following would be better as it would be more explicit

type poolLocal struct {
      _     [64]byte     // Prevents false sharing.
      private interface{}   // Can be used only by the respective P.
      shared  []interface{} // Can be used by any P.
      Mutex                 // Protects shared.
      _     [64]byte     // Prevents false sharing.
}

huangapple
  • 本文由 发表于 2017年1月17日 20:52:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/41697727.html
匿名

发表评论

匿名网友

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

确定