Quantcast
Channel: GameDev.net
Viewing all articles
Browse latest Browse all 17825

Cache In A Multi-Core Environment

$
0
0

Cache In A Multi-Core Environment


In my previous article I discussed the use of cache and some practices that can provide increased performance while also teaching you what cache is. I also stated that cache in a multicore environment is a whole other topic so I’ve written this article to cover the different considerations that come along with Multicore Programming.

Why does it matter if we’re using two cores?


Cache comes in levels, typically 3 each with their own group of cores that can access it, L1 Cache is only visible to a single core with each core having it’s own private cache and is the fastest of all caches. L2 Cache is usually visible to a group of cores, for instance the AMD 8150 shares L2 Cache between two cores and finally there’s L3 Cache that is accessible to all cores and is the slowest of caches, but still much faster in comparison to RAM.

Now that we know that there are different banks of cache for each core, what happens when two cores are accessing the same memory? If there was no system in place then both cores would cache the memory, then lets say one core wrote to that memory, This would be visible in memory, although the other core would still have it’s cache of the old value. To solve this when a core writes to it’s cached memory; Any other core that stores that cache line will be removed or updated, which is where our problem comes into play.

Let’s say you have 2 Integers on a single cache line and each core was writing to an integer each that are next to each other in an array, although they’re not the same variables and it won’t cause any unexpected results, because they’re on the same cache line. Every time one core writes to that memory, the other core loses its cache. This is referred to as False Sharing and there’s a simple solution to this, the hardest part is determining if you’re having this problem.

False Sharing


False Sharing can hinder the performance for any program. For this example I’ll go through the optimisations I did on a single producer single consumer queue and provide a few steps to solving most of your False Sharing problems. To test the queue I have two threads, one writing integers from 0 to 1 million and another reading them and checking if they’re all in order. The queue doesn’t undergo any resizing and is allocated with enough capacity for 1 million objects.

template<typedef T>
class alignas(64) Queue{
    T* data_;
    size_t push_position_;
    size_t pop_position_;
    std::atomic<size_t> size_;
    size_t capacity_;
};

The problem with this code is that all the variables are packed together with no spacing together, the whole structure would fit on up to two cache lines. This is perfect if we’re in a single core environment, although separate cores access pop_position and push_position therefor there’s high contention between these cache lines in a multicore Environment.

I break the problem down into a shared read section; shared write section and one section for each thread. A section may be larger than a single cache line and may require two cache lines to implement, it’s for this reason I call them a section. Our first step would be to determine what memory belongs to what section. With data_ and capacity_ both being shared, but rarely written to, they therefor belong to the shared read cache line, size_ is the only variable that is a shared write and push and pop both belong to their own cache line as each thread uses one each. In this example that leaves us with 4 cache lines. This leaves us with

template<typedef T>
class alignas(64) Queue{
    // Producers C-Line
    size_t push_position_;
    char pad_p[64 - sizeof(size_t)];
    // Consumers C-Line
    size_t pop_position_;
    char pad_c[64 - sizeof(size_t)];
    // Shared Read C-Line
    T* data_;
    size_t capacity_;
    char pad_sr[64 - sizeof(size_t) - sizeof(T*)];
    // Shared Write C-Line
    std::atomic<size_t> size_;
    char pad_sw[64 - sizeof(std::atomic<size_t>)];
};

Notice that the alignas(n) this is a new keyword added in C++14. The keyword ensures that the structure is aligned to a multiple of n bytes in memory and therefor allows us to assume that our first variable will be placed at the start of a cache line, which is vital for our separation.

Before accounting for False sharing, to push and pop 1 million Integers it took 60ms, but after accounting for False Sharing it’s been reduced to 34ms on a Intel Core I5 3210M @ 2.5Ghz. The majority of the time comes from the atomic access, which we use to check to see if there’s room to push and anything to pop. You could potentially optimise the atomic access out of most of the pushes by remembering how many objects can be pushed and popped until your next size check, this way we can lower the atomic access and dramatically improve performance again.

Example Source

While on the same subject of False Sharing, another example would occur when storing data within an array and having a number of threads access that array. Lets think about pool of threads which keep count how much work they’ve done and store it in an array. We need access to these variables to check how much work’s been done while running.

	int work_done[n];

An easy mistake to make, but would result in a plethora of cache misses. As each core goes to increment it’s work_done it would invalidate the other cores cache. A solution to this would be to turn the array into an array of pointers to store a pointer to a local variable inside the thread, this would require that we pass a pointer to work_done so we can populate that pointer with the address of the local variable. From a synthetic test where the worker thread is only iterating on work_done, we can see over 5 seconds of iteration across 4 cores we get a result of ~890M iterations per core while once we’d accounted for False Sharing and utilized local variables we get a result of ~1.8B iterations per core which is a ~2x improvement on the I5 3210M @ 2.5Ghz. The same test on an AMD 8150 @ 4.2Ghz reached 44M iterations with False Sharing, while without we reached 2.3B iterations which is a shocking ~52x improvement in speed, I had to double check this result because it’s left me in disbelief**! In this case we use a local variable instead of padding between all the variables to save space, but both would work equally as well.

Example Source

Volatile Data


Another problem that isn’t exactly cache related, although it’s still important is the use of volatiles. A register is a tiny piece of memory that’s specific to each core and can be accessed in typically 1 cycle. The key difference between a register and cache is that a register is local memory and isn’t supposed to be a fast clone of what’s in RAM like cache is. A program will quite often copy a value from RAM into a register, work on it there and then write back to RAM with the result. In a single threaded program this is fine, but in the situation where you have two cores editing the same integer, both may take a local copy of the integer, edit it and then write back. Each core would be overwriting the other’s result, because they never saw the other cores work. C++ has a solution to this assuming that you’ve prevented both cores from reading and writing at the exact same time, because they can still interfere, if this assumption isn't possible than a std::atomic is required. The volatile keyword tells the compiler to never assume that the value hasn't been changed, this prevents specific optimisations that would break your code, but now I’m getting into Multicore Programming and not cache for multicore programs.

	volatile int x = 0;

Summary


  • Only use an Atomic when necessary, check if a volatile will meet your needs first
  • Keep classes with multicore access segmented by cache lines to eliminate False Sharing
  • Local variables are preferred over sharing data outside of the thread

Conclusion


False Sharing can be a problematic side affect of multicore programming which should be a consideration whenever two cores use data in proximity to one another. From these tests on an Intel 3210M we can see that by eliminating False Sharing we receive a ~2x performance boost, obviously this would differ on different hardware. A tool that can be useful with multicore programming is volatile variable, although these have their own issues when two cores write to the variable, they can still be a useful replacement to an atomic in read only situations.

Notes


* AMD 8150 is tested on Windows 8.1 with Visual Studio 2013 and Intel 3210M is tested on OSX 10.10 LLVM 6.1.0.

** After seeing such a large difference, I went looking for a cause to such dramatic performance loss; I found that the L3 cache on the Bulldozer architecture is broken into 2MB per module (2 cores) that cannot be accessed by other modules [1]. Sharing would result in a cache miss all the way to RAM, while the I5 3210M shares it L3 Cache between all cores and would only need to go to the L3 cache in the case of a cache miss. This wouldn’t be a problem if the operating system had placed the threads onto the two cores in a module. I kept running the tests with 2 threads until the result went from 44M to 1.2B per thread, assuming that in these cases the threads were placed on the same module and therefor shared L3 cache. This is a perfect example of the importance of testing your software on different hardware.


[1] isscc.org/doc/2011/isscc2011.advanceprogrambooklet_abstracts.pdf pg. 40

Viewing all articles
Browse latest Browse all 17825

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>