multithreadinggomutexfalse-sharing

Strange code for preventing false sharing


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?


Solution

  • 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.
    }