False sharing
In this section, we’ll study a common issue with multithreaded applications called false sharing.
We already know that the ideal implementation of a multithreaded application is minimizing the data that’s shared among its different threads. Ideally, we should share data just for read access because in that case, we don’t need to synchronize the threads to access the shared data and thus we don’t need to pay the runtime cost and deal with issues such as deadlock and livelock.
Now, let’s consider a simple example: four threads run in parallel, generate random numbers, and calculate their sum. Each thread works independently, generating random numbers and calculating the sum stored in a variable just written by itself. This is the ideal (though for this example, a bit contrived) application, with threads working independently without any shared data.
The following code is the full source for the example we’re going to analyze...