#include #include #include #include #include #include #define FALSE_SHARING 1 #define ITER_MAX 1 #define DIM (21000) #define CPU_MAX 16 static volatile int matrix[DIM][DIM]; static volatile int result[CPU_MAX]; static volatile int cpuUsed; #define min(a, b) ((a) <= (b) ? (a) : (b)) /** Variables annadidas **/ #define P 4 static int impares_p[P]; void *body(void *cpu_nr) { int i, j,p = *((int *)cpu_nr); int pStart = p * DIM/P; int pEnd = (p+1) * DIM/P; for(i = pStart; i < pEnd; i++) for(j = 0; j < DIM; j++) if((matrix[i][j] % 2) != 0) impares_p[p]++; return NULL; } int main(int argc, char **argv) { pthread_t thr [CPU_MAX]; int nombre[CPU_MAX]; int i, j, k; cpu_set_t set; int cpuCount; int odds = 0; if(argc != 2) { printf("Use: false_sharing NumberOfCPUs\n"); goto exception; } /* Getting number of CPUs */ if (0 > (cpuCount = (int)sysconf( _SC_NPROCESSORS_ONLN ))) { perror( "sysconf" ); return -1; } if(cpuCount < (cpuUsed = atoi(argv[1]))) { printf("Not enough CPUs\n"); exit(1); } printf("SMP with %d Cpus Available. \nWorking with %d cpus\n", cpuCount, cpuUsed); CPU_ZERO( &set ); for(k = 0; k < cpuUsed; k++) CPU_SET( k, &set ); if (0 > sched_setaffinity( 0, sizeof( cpu_set_t ), &set )) goto exception; for(i = 0; i < cpuUsed ; i++) { result[i] = 0; nombre[i] = i; } for(i = 0; i < DIM; i++) { for(j = 0; j < DIM; j++) matrix[i][j] = DIM*i + j; } for(i = 0; i < cpuUsed; i++) if(pthread_create(&thr[i], NULL, body, &nombre[i])) goto exception; for(i = 0; i < cpuUsed; i++) if(pthread_join(thr[i], NULL)) goto exception; for( i = 0; i < cpuUsed ; i++) odds += result[i]; int impares=0; int p; for(p = 0; p < P; p++ ) impares += impares_p[p]; printf("Casillas impares : %d\n", DIM*DIM/2); printf("Casillas impares obtenidas: %d\n", impares/ITER_MAX); return 0; exception: perror(""); return 1; }