32
edits
Changes
→Sources
[[File:MESIDIAGRAM123.PNG]]
== Sources ==
<pre>
#include <iostream>
#include <thread>
#include <chrono>
using namespace std;
using namespace chrono;
// Constants to control the program
const int NUM_THREADS = 2;
const int NUM_ITERATIONS = 100000000;
const int CACHE_LINE_SIZE = 64;
// Define a counter struct to ensure cache line alignment
struct alignas(CACHE_LINE_SIZE) Counter {
volatile long long value; // the counter value
char padding[CACHE_LINE_SIZE - sizeof(long long)]; // padding to align the struct to cache line size
};
// Define two counter variables
Counter counter1, counter2;
// Function to increment counter 1
void increment1() {
for (int i = 0; i < NUM_ITERATIONS; i++) {
counter1.value++;
}
}
// Function to increment counter 2
void increment2() {
for (int i = 0; i < NUM_ITERATIONS; i++) {
counter2.value++;
}
}
// Function to check the runtime of the program
void checkRuntime(high_resolution_clock::time_point start_time, high_resolution_clock::time_point end_time) {
auto duration = duration_cast<milliseconds>(end_time - start_time).count();
cout << "Runtime: " << duration << " ms" << endl;
}
int main() {
// Print the cache line size
cout << "Cache line size: " << CACHE_LINE_SIZE << " bytes" << endl;
// Record the start time
high_resolution_clock::time_point start_time = high_resolution_clock::now();
// Create two threads to increment the counters
thread t1(increment1);
thread t2(increment2);
// Wait for the threads to finish
t1.join();
t2.join();
// Record the end time
high_resolution_clock::time_point end_time = high_resolution_clock::now();
// Check the runtime of the program
checkRuntime(start_time, end_time);
// Print the final counter values
cout << "Counter 1: " << counter1.value << endl;
cout << "Counter 2: " << counter2.value << endl;
return 0;
}
</pre>
== Sources ==