False sharing

1 minute read

Overview

거짓 공유는 캐싱 메커니즘에 의해 관리되는 가장 작은 리소스 블록 크기의 분산되고 일관된 캐시가 있는 시스템에서 발생할 수 있는 성능 저하 사용 패턴이다.

  • 두 프로세서들이 각기 다른 다른 주소에 write를 하려고 하나, 이 주소들이 같은 캐시 라인에 매핑된 조건을 말한다.
  • 프로세서들의 캐시 사이에서 캐시 라인을 서로 쓰는 상황이 발생하게 되면, cache coherence protocol으로 인해 상당한 양의 통신을 발생시킨다.

Example

#include <cstdio>
#include <chrono>
#include <pthread.h>

constexpr size_t
#if defined(__cpp_lib_hardware_interference_size)
  CACHE_LINE_SIZE = hardware_destructive_interference_size,
#else
  CACHE_LINE_SIZE = 64,
#endif
  MAX_THREADS = 8, MANY_ITERATIONS = 1000000000;

void* worker(void* arg) {
  volatile int* counter = (int*)arg;
  for (int i = 0; i < MANY_ITERATIONS; i++) (*counter)++;
  return NULL;
}
void test1(int num_threads) {
  auto begin = std::chrono::high_resolution_clock::now();

  pthread_t threads[MAX_THREADS];
  int counter[MAX_THREADS];

  for (int i = 0; i < num_threads; i++)
    pthread_create(&threads[i], NULL, &worker, &counter[i]);
  for (int i = 0; i < num_threads; i++)
    pthread_join(threads[i], NULL);

  auto end = std::chrono::high_resolution_clock::now();
  auto elapsed =
      std::chrono::duration_cast<std::chrono::nanoseconds>(end - begin);
  printf("Time measured: %.3f seconds.\n", elapsed.count() * 1e-9);
}

struct padded_t
{
  int counter;
  char padding[CACHE_LINE_SIZE - sizeof(int)];
};
void test2(int num_threads) {
  auto begin = std::chrono::high_resolution_clock::now();

  pthread_t threads[MAX_THREADS];
  padded_t counter[MAX_THREADS];

  for (int i = 0; i < num_threads; i++)
    pthread_create(&threads[i], NULL, &worker, &(counter[i].counter));
  for (int i = 0; i < num_threads; i++)
    pthread_join(threads[i], NULL);

  auto end = std::chrono::high_resolution_clock::now();
  auto elapsed =
      std::chrono::duration_cast<std::chrono::nanoseconds>(end - begin);
  printf("Time measured: %.3f seconds.\n", elapsed.count() * 1e-9);
}

int main()
{
    test1(8);
    test2(8);
}

위 코드를 실행했을 때, 아래와 같은 결과를 얻을 수 있다.

Time measured: 2.946 seconds.
Time measured: 2.533 seconds.

참고자료

False sharing Lecture 10: Cache Coherence

Leave a comment