Changes

Jump to: navigation, search

DPS921/Group 8

1,040 bytes added, 10:52, 26 November 2018
Critical construct
== Critical construct ==
The other way to eliminating false sharing is to implement a mutual exclusion construct. This the better method than using padding as there is no wasting of memory and data access is not hindered due to cache line invalidation. Programming a mutual exclusion implementation is done by using the critical construct in an op environment. The critical construct restricts statements to a single thread to process at a time, making variables local to a single thread ensures that multiple threads do not write data to the same cache line.
 
______________________________________________________________________________________________________________________________________________________________
 
<nowiki>
#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <chrono>
#include <algorithm>
#include <omp.h>
#include "pch.h"
using namespace std::chrono;
 
struct MyStruct
{
float value;
//int padding[24];
};
 
int main(int argc, char** argv)
{
MyStruct testArr[4];
 
float partial_val = 0.0;
 
int threads_used;
omp_set_num_threads(4);
double start_time = omp_get_wtime();
 
#pragma omp parallel for
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 10000; j++) {
partial_val = testArr[i].value + 2;
}
#pragma omp critical
testArr[i].value += partial_val;
}
 
double time = omp_get_wtime() - start_time;
std::cout << "Execution Time: " << time << std::endl;
 
return 0;
}
</nowiki>
______________________________________________________________________________________________________________________________________________________________
 
[[File:4threads_critical.jpg|1000px]]
42
edits

Navigation menu