Changes

Jump to: navigation, search

GPU621/Group 1

2,332 bytes added, 19:46, 9 April 2023
Solution
The updated code, which addresses false sharing and optimization, is provided below:
 
<pre>
 
#include <iostream>
#include <thread>
#include <chrono>
#include <atomic>
 
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 with padding for cache line alignment
struct alignas(CACHE_LINE_SIZE) Counter {
atomic<long long> value; // the counter value
char padding[CACHE_LINE_SIZE - sizeof(atomic<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;
// Run the program using a single thread
cout << "Running program using a single thread" << endl;
high_resolution_clock::time_point start_time = high_resolution_clock::now();
for (int i = 0; i < NUM_ITERATIONS; i++) {
counter1.value++;
counter2.value++;
}
high_resolution_clock::time_point end_time = high_resolution_clock::now();
checkRuntime(start_time, end_time);
cout << "Counter 1: " << counter1.value << endl;
cout << "Counter 2: " << counter2.value << endl;
 
// Run the program using multiple threads
cout << "Running program using " << NUM_THREADS << " threads" << endl;
counter1.value = 0;
counter2.value = 0;
start_time = high_resolution_clock::now();
thread t1(increment1);
thread t2(increment2);
t1.join();
t2.join();
end_time = high_resolution_clock::now();
checkRuntime(start_time, end_time);
cout << "Counter 1: " << counter1.value << endl;
cout << "Counter 2: " << counter2.value << endl;
 
return 0;
}
 
 
</pre>
== Sources ==
25
edits

Navigation menu