False sharing
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.
Leave a comment