Should work

main
Gasper Spagnolo 2022-11-22 09:25:17 +01:00
parent bb5db76bdc
commit dc7147eb8d
2 changed files with 23 additions and 5 deletions

Binary file not shown.

View File

@ -5,7 +5,7 @@
#include <unistd.h> #include <unistd.h>
#include <math.h> #include <math.h>
#define N_THREADS 8 #define N_THREADS 9
#define N_DIMENSIONS 200000000 #define N_DIMENSIONS 200000000
pthread_barrier_t b; pthread_barrier_t b;
@ -14,6 +14,10 @@ long *q_s;
double res[N_THREADS]; double res[N_THREADS];
int active_threads[N_THREADS]; int active_threads[N_THREADS];
// odd number of threads lock
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
pthread_spinlock_t slock;
void setup() { void setup() {
p_s = (long *) malloc(N_DIMENSIONS * sizeof(long)); p_s = (long *) malloc(N_DIMENSIONS * sizeof(long));
q_s = (long *) malloc(N_DIMENSIONS * sizeof(long)); q_s = (long *) malloc(N_DIMENSIONS * sizeof(long));
@ -40,6 +44,16 @@ void *calculate(void* arg) {
pthread_barrier_wait( &b ); pthread_barrier_wait( &b );
int n_threads = N_THREADS; int n_threads = N_THREADS;
if(n_threads % 2 == 1) {
if ( *myrank == N_THREADS - 1) {
res[*myrank - 1] += res[*myrank];
active_threads[*myrank] = -1;
}
n_threads--;
}
pthread_barrier_wait( &b );
if (n_threads != 1) { if (n_threads != 1) {
@ -76,11 +90,14 @@ int main() {
double dt = omp_get_wtime(); // start timing double dt = omp_get_wtime(); // start timing
int p[N_THREADS]; int p[N_THREADS];
if(N_THREADS %2 != 0 && N_THREADS >= 2) { //if(N_THREADS %2 != 0 && N_THREADS >= 2) {
printf("Number of threads must be even!\n"); // printf("Number of threads must be even!\n");
return 1; // return 1;
} //}
//
// barrier & lock
pthread_barrier_init( &b, NULL, N_THREADS ); pthread_barrier_init( &b, NULL, N_THREADS );
pthread_spin_init(&slock, PTHREAD_PROCESS_PRIVATE);
for(int i = 0; i < N_THREADS; i++ ) { for(int i = 0; i < N_THREADS; i++ ) {
p[i] = i; p[i] = i;
@ -90,6 +107,7 @@ int main() {
for(int i=0; i<N_THREADS; i++) for(int i=0; i<N_THREADS; i++)
pthread_join(t[i], NULL); pthread_join(t[i], NULL);
pthread_spin_destroy(&slock);
dt = omp_get_wtime() - dt; // finish timing dt = omp_get_wtime() - dt; // finish timing
printf("Execution time: %lf, caluclation result: %lf ", dt, sqrt(res[0])); printf("Execution time: %lf, caluclation result: %lf ", dt, sqrt(res[0]));