


Recently, I was working on a multi-threaded implementation of a function to calculate the Poisson distribution (amath_pdist). The goal was to divide the workload across multiple threads to improve performance, especially for large arrays. However, instead of achieving the expected speedup, I noticed a significant slowdown as the size of the array increased.
After some investigation, I discovered the culprit: false sharing. In this post, I’ll explain what false sharing is, show the original code causing the problem, and share the fixes that led to a substantial performance improvement.
The Problem: False Sharing in Multi-threaded Code
False sharing happens when multiple threads work on different parts of a shared array, but their data resides in the same cache line. Cache lines are the smallest unit of data transferred between memory and the CPU cache (typically 64 bytes). If one thread writes to part of a cache line, it invalidates the line for other threads—even if they’re working on logically independent data. This unnecessary invalidation leads to significant performance degradation due to repeated reloading of cache lines.
Here’s a simplified version of my original code:
void *calculate_pdist_segment(void *data) { struct pdist_segment *segment = (struct pdist_segment *)data; size_t interval_a = segment->interval_a, interval_b = segment->interval_b; double lambda = segment->lambda; int *d = segment->data; for (size_t i = interval_a; i pdist[i] = pow(lambda, d[i]) * exp(-lambda) / tgamma(d[i] + 1); } return NULL; } double *amath_pdist(int *data, double lambda, size_t n_elements, size_t n_threads) { double *pdist = malloc(sizeof(double) * n_elements); pthread_t threads[n_threads]; struct pdist_segment segments[n_threads]; size_t step = n_elements / n_threads; for (size_t i = 0; i <hr> <h3> Where the Problem Occurs </h3> <p>In the above code:</p>
- The array pdist is shared among all threads.
- Each thread writes to a specific range of indices (interval_a to interval_b).
- At segment boundaries, adjacent indices may reside in the same cache line. For example, if pdist[249999] and pdist[250000] share a cache line, Thread 1 (working on pdist[249999]) and Thread 2 (working on pdist[250000]) invalidate each other’s cache lines.
This issue scaled poorly with larger arrays. While the boundary issue might seem small, the sheer number of iterations magnified the cost of cache invalidations, leading to seconds of unnecessary overhead.
The Solution: Align Memory to Cache Line Boundaries
To fix the problem, I used posix_memalign to ensure that the pdist array was aligned to 64-byte boundaries. This guarantees that threads operate on completely independent cache lines, eliminating false sharing.
Here’s the updated code:
double *amath_pdist(int *data, double lambda, size_t n_elements, size_t n_threads) { double *pdist; if (posix_memalign((void **)&pdist, 64, sizeof(double) * n_elements) != 0) { perror("Failed to allocate aligned memory"); return NULL; } pthread_t threads[n_threads]; struct pdist_segment segments[n_threads]; size_t step = n_elements / n_threads; for (size_t i = 0; i <hr> <h3> Why Does This Work? </h3> <ol> <li> <p><strong>Aligned Memory</strong>:</p> <ul> <li>Using posix_memalign, the array starts on a cache line boundary.</li> <li>Each thread’s assigned range aligns neatly with cache lines, preventing overlap.</li> </ul> </li> <li> <p><strong>No Cache Line Sharing</strong>:</p> <ul> <li>Threads operate on distinct cache lines, eliminating invalidations caused by false sharing.</li> </ul> </li> <li> <p><strong>Improved Cache Efficiency</strong>:</p> <ul> <li>Sequential memory access patterns align well with CPU prefetchers, further boosting performance.</li> </ul> </li> </ol> <hr> <h3> Results and Takeaways </h3> <p>After applying the fix, the runtime of the amath_pdist function dropped significantly. For a dataset I was testing, the wall clock time dropped from <strong>10.92 seconds to 0.06 seconds</strong>.</p> <h4> Key Lessons: </h4> <ol> <li> <strong>False sharing</strong> is a subtle yet critical issue in multi-threaded applications. Even small overlaps at segment boundaries can degrade performance.</li> <li> <strong>Memory alignment</strong> using posix_memalign is a simple and effective way to solve false sharing. Aligning memory to cache line boundaries ensures threads operate independently.</li> <li>Always analyze your code for cache-related issues when working with large arrays or parallel processing. Tools like perf or valgrind can help pinpoint bottlenecks.</li> </ol> <p>Thank you for reading!</p> <p>For anyone curious about the code, you can find it here</p>
The above is the detailed content of Understanding and Solving False Sharing in Multi-threaded Applications with an actual issue I had. For more information, please follow other related articles on the PHP Chinese website!

C is not dead, but has flourished in many key areas: 1) game development, 2) system programming, 3) high-performance computing, 4) browsers and network applications, C is still the mainstream choice, showing its strong vitality and application scenarios.

The main differences between C# and C are syntax, memory management and performance: 1) C# syntax is modern, supports lambda and LINQ, and C retains C features and supports templates. 2) C# automatically manages memory, C needs to be managed manually. 3) C performance is better than C#, but C# performance is also being optimized.

You can use the TinyXML, Pugixml, or libxml2 libraries to process XML data in C. 1) Parse XML files: Use DOM or SAX methods, DOM is suitable for small files, and SAX is suitable for large files. 2) Generate XML file: convert the data structure into XML format and write to the file. Through these steps, XML data can be effectively managed and manipulated.

Working with XML data structures in C can use the TinyXML or pugixml library. 1) Use the pugixml library to parse and generate XML files. 2) Handle complex nested XML elements, such as book information. 3) Optimize XML processing code, and it is recommended to use efficient libraries and streaming parsing. Through these steps, XML data can be processed efficiently.

C still dominates performance optimization because its low-level memory management and efficient execution capabilities make it indispensable in game development, financial transaction systems and embedded systems. Specifically, it is manifested as: 1) In game development, C's low-level memory management and efficient execution capabilities make it the preferred language for game engine development; 2) In financial transaction systems, C's performance advantages ensure extremely low latency and high throughput; 3) In embedded systems, C's low-level memory management and efficient execution capabilities make it very popular in resource-constrained environments.

The choice of C XML framework should be based on project requirements. 1) TinyXML is suitable for resource-constrained environments, 2) pugixml is suitable for high-performance requirements, 3) Xerces-C supports complex XMLSchema verification, and performance, ease of use and licenses must be considered when choosing.

C# is suitable for projects that require development efficiency and type safety, while C is suitable for projects that require high performance and hardware control. 1) C# provides garbage collection and LINQ, suitable for enterprise applications and Windows development. 2)C is known for its high performance and underlying control, and is widely used in gaming and system programming.

C code optimization can be achieved through the following strategies: 1. Manually manage memory for optimization use; 2. Write code that complies with compiler optimization rules; 3. Select appropriate algorithms and data structures; 4. Use inline functions to reduce call overhead; 5. Apply template metaprogramming to optimize at compile time; 6. Avoid unnecessary copying, use moving semantics and reference parameters; 7. Use const correctly to help compiler optimization; 8. Select appropriate data structures, such as std::vector.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Dreamweaver Mac version
Visual web development tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver CS6
Visual web development tools

Atom editor mac version download
The most popular open source editor

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.
