Main.c 20.5 KB
Newer Older
1
2
3
#include <stdio.h>
#include <stdlib.h>
#include <mpi.h>
iker_martin's avatar
iker_martin committed
4
5
#include <fcntl.h>
#include <sys/stat.h>
6
#include <pthread.h>
7
#include "../IOcodes/read_ini.h"
8
#include "../IOcodes/results.h"
iker_martin's avatar
iker_martin committed
9
10
#include "../malleability/ProcessDist.h"
#include "../malleability/CommDist.h"
11
12
13

#define ROOT 0

iker_martin's avatar
iker_martin committed
14
15
16
int work();
void Sons_init();

17
int checkpoint(int iter, int state, MPI_Request **comm_req);
iker_martin's avatar
iker_martin committed
18
void TC(int numS);
19
20
int start_redistribution(int numS, MPI_Request **comm_req);
int check_redistribution(int iter, MPI_Request **comm_req);
21
22
23
24
25
int end_redistribution(int iter);

int thread_creation();
int thread_check();
void* thread_async_work(void* void_arg);
iker_martin's avatar
iker_martin committed
26

27
void iterate(double *matrix, int n, int async_comm);
28
void computeMatrix(double *matrix, int n);
29
double computePiSerial(int n);
30
31
void initMatrix(double **matrix, int n);

32
void init_group_struct(char *argv[], int argc, int myId, int numP);
33
34
35
void init_application();
void free_application_data();

36
void print_general_info(int myId, int grp, int numP);
37
int print_final_results();
iker_martin's avatar
iker_martin committed
38
int create_out_file(char *nombre, int *ptr, int newstdout);
39

iker_martin's avatar
iker_martin committed
40
41
42
43
typedef struct {
  int myId;
  int numP;
  int grp;
44
  int iter_start;
45
  int argc;
iker_martin's avatar
iker_martin committed
46

47
48
  int numS; // Cantidad de procesos hijos
  int commAsync;
iker_martin's avatar
iker_martin committed
49
50
  MPI_Comm children, parents;
  char **argv;
51
  char *sync_array, *async_array;
iker_martin's avatar
iker_martin committed
52
53
} group_data;

54
55
56
57
58
59
typedef struct {
  int myId, numP, numS, adr;
  MPI_Comm children;
  char *sync_array;
} thread_data;

iker_martin's avatar
iker_martin committed
60
61
configuration *config_file;
group_data *group;
62
results_data *results;
63
int run_id = 0; // Utilizado para diferenciar más fácilmente ejecuciones en el análisis
64

65
66
pthread_t async_thread; // TODO Cambiar de sitio?

67
int main(int argc, char *argv[]) {
68
    int numP, myId, res;
iker_martin's avatar
iker_martin committed
69
    int req;
70

71
    MPI_Init_thread(&argc, &argv, MPI_THREAD_SINGLE, &req);
72
    MPI_Comm_size(MPI_COMM_WORLD, &numP);
iker_martin's avatar
iker_martin committed
73
74
    MPI_Comm_rank(MPI_COMM_WORLD, &myId);

75
    init_group_struct(argv, argc, myId, numP);
76
77
78
79
80
81
82

    MPI_Comm_get_parent(&(group->parents));
    if(group->parents == MPI_COMM_NULL ) { // Si son el primer grupo de procesos, recogen la configuracion inicial
      init_application();
    } else { // Si son procesos hijos deben comunicarse con las padres
      Sons_init();
    }
iker_martin's avatar
iker_martin committed
83

84
85
86
    if(group->grp == 0) {
      MPI_Barrier(MPI_COMM_WORLD);
      results->exec_start = MPI_Wtime();
87
    }
88

89
    res = work();
90

91
92
93
    if(res) { // Se he llegado al final de la aplicacion
      MPI_Barrier(MPI_COMM_WORLD);
      results->exec_time = MPI_Wtime() - results->exec_start;
94
    }
95

96
97
98
    print_final_results();

    free_application_data();
99
100
101
102
103
    MPI_Finalize();
    return 0;
}

/*
104
105
106
107
108
109
110
111
112
 * Función de trabajo principal.
 *
 * Incializa los datos para realizar el computo y a continuacion
 * pasa a realizar "maxiter" iteraciones de computo.
 *
 * Terminadas las iteraciones realiza el redimensionado de procesos.
 * Si el redimensionado se realiza de forma asincrona se 
 * siguen realizando iteraciones de computo hasta que termine la 
 * comunicacion asincrona y realizar entonces la sincrona.
113
114
115
116
 *
 * Si el grupo de procesos es el ultimo que va a ejecutar, se devuelve
 * el valor 1 para indicar que no se va a seguir trabajando con nuevos grupos
 * de procesos. En caso contrario se devuelve 0.
117
 */
iker_martin's avatar
iker_martin committed
118
int work() {
119
  int iter, maxiter, state, res;
120
  double *matrix;
121
  MPI_Request *async_comm;
122

iker_martin's avatar
iker_martin committed
123
  maxiter = config_file->iters[group->grp];
124
  //initMatrix(&matrix, config_file->matrix_tam);
125
  state = MAL_COMM_UNINITIALIZED;
iker_martin's avatar
iker_martin committed
126

127
  res = 0;
128
  for(iter=group->iter_start; iter < maxiter; iter++) {
129
    iterate(matrix, config_file->matrix_tam, state);
130
  }
131
  state = checkpoint(iter, state, &async_comm);
132
  
133
134
  iter = 0;
  while(state == MAL_ASYNC_PENDING) {
135
    iterate(matrix, config_file->matrix_tam, state);
136
    iter++;
137
    state = checkpoint(iter, state, &async_comm);
138
  }
139
  
140
141
  if(config_file->resizes - 1 == group->grp) res=1;
  return res;
142
143
}

144
145
146
147
148
149
150
151
/*
 * Se realiza el redimensionado de procesos por parte de los padres.
 *
 * Se crean los nuevos procesos con la distribucion fisica elegida y
 * a continuacion se transmite la informacion a los mismos.
 *
 * Si hay datos asincronos a transmitir, primero se comienza a
 * transmitir estos y se termina la funcion. Se tiene que comprobar con
152
 * llamando a la función de nuevo que se han terminado de enviar
153
154
155
156
157
158
 *
 * Si hay ademas datos sincronos a enviar, no se envian aun.
 *
 * Si solo hay datos sincronos se envian tras la creacion de los procesos
 * y finalmente se desconectan los dos grupos de procesos.
 */
159
160
161
162
163
164
int checkpoint(int iter, int state, MPI_Request **comm_req) {
  
  if(state == MAL_COMM_UNINITIALIZED) {
    // Comprobar si se tiene que realizar un redimensionado
    if(config_file->iters[group->grp] > iter || config_file->resizes == group->grp + 1) {return MAL_COMM_UNINITIALIZED;}

165
    group->numS = config_file->procs[group->grp +1];
166
167

      results->spawn_start = MPI_Wtime();
168
    TC(group->numS);
169
      results->spawn_time[group->grp] = MPI_Wtime() - results->spawn_start;
170

171
    state = start_redistribution(group->numS, comm_req);
172

173
  } else if(state == MAL_ASYNC_PENDING) {
174
175
176
    state = thread_check();
    if(state == MAL_COMM_COMPLETED) end_redistribution(iter);
    //state = check_redistribution(iter, comm_req);
177
  }
iker_martin's avatar
iker_martin committed
178

179
180
  return state;
}
iker_martin's avatar
iker_martin committed
181

182
183
184
185
186
187
188
/*
 * Se encarga de realizar la creacion de los procesos hijos.
 */
void TC(int numS){
  // Inicialización de la comunicación con SLURM
  int dist = config_file->phy_dist[group->grp +1];
  init_slurm_comm(group->argv, group->myId, numS, ROOT, dist, COMM_SPAWN_SERIAL);
iker_martin's avatar
iker_martin committed
189

190
191
192
193
194
195
196
  // Esperar a que la comunicación y creación de procesos
  // haya finalizado
  int test = -1;
  while(test != MPI_SUCCESS) {
    test = check_slurm_comm(group->myId, ROOT, MPI_COMM_WORLD, &(group->children));
  }
}
iker_martin's avatar
iker_martin committed
197

198
199
200
201
202
203
204
205
206
207
208
209
210
211
/*
 * Comienza la redistribucion de los datos con el nuevo grupo de procesos.
 *
 * Primero se envia la configuracion a utilizar al nuevo grupo de procesos y a continuacion
 * se realiza el envio asincrono y/o sincrono si lo hay.
 *
 * En caso de que haya comunicacion asincrona, se comienza y se termina la funcion 
 * indicando que se ha comenzado un envio asincrono.
 *
 * Si no hay comunicacion asincrono se pasa a realizar la sincrona si la hubiese.
 *
 * Finalmente se envian datos sobre los resultados a los hijos y se desconectan ambos
 * grupos de procesos.
 */
212
int start_redistribution(int numS, MPI_Request **comm_req) {
iker_martin's avatar
iker_martin committed
213
214
215
216
217
  int rootBcast = MPI_PROC_NULL;
  if(group->myId == ROOT) rootBcast = MPI_ROOT;

  // Enviar a los hijos que grupo de procesos son
  MPI_Bcast(&(group->grp), 1, MPI_INT, rootBcast, group->children);
218
  MPI_Bcast(&run_id, 1, MPI_INT, rootBcast, group->children);
iker_martin's avatar
iker_martin committed
219
220
  send_config_file(config_file, rootBcast, group->children);

221
  if(config_file->adr > 0) {
222
    results->async_start = MPI_Wtime();
223
224
225
226
    //send_async(group->async_array, config_file->adr, group->myId, group->numP, ROOT, group->children, numS, comm_req, config_file->aib);
    return thread_creation();
    //return MAL_ASYNC_PENDING;

227
  } 
228
229
230
231
232
233
234
235
236
237
238
  return end_redistribution(0);
}

/*
 * Crea una hebra para ejecutar una comunicación en segundo plano.
 */
int thread_creation() {
  if(pthread_create(&async_thread, NULL, thread_async_work, NULL)) {
    printf("Error al crear el hilo\n");
    MPI_Abort(MPI_COMM_WORLD, -1);
    return -1;
iker_martin's avatar
iker_martin committed
239
  }
240
241
  return MAL_ASYNC_PENDING;
}
242

243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
/*
 * Comprobación por parte de una hebra maestra que indica
 * si una hebra esclava ha terminado su comunicación en segundo plano.
 *
 * El estado de la comunicación es devuelto al finalizar la función. 
 */
int thread_check() {
  if(group->commAsync == MAL_COMM_COMPLETED) {
    if(pthread_join(async_thread, NULL)) {
      printf("Error al esperar al hilo\n");
      MPI_Abort(MPI_COMM_WORLD, -1);
      return -2;
    } 
    return MAL_COMM_COMPLETED;
  }
iker_martin's avatar
iker_martin committed
258

259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
  return MAL_ASYNC_PENDING;
}

/*
 * Función ejecutada por una hebra.
 * Ejecuta una comunicación síncrona con los hijos que
 * para el usuario se puede considerar como en segundo plano.
 *
 * Cuando termina la comunicación la hebra maestra puede comprobarlo
 * por el valor "commAsync".
 */
void* thread_async_work(void* void_arg) {
  send_sync(group->async_array, config_file->adr, group->myId, group->numP, ROOT, group->children, group->numS);
  group->commAsync = MAL_COMM_COMPLETED;
  pthread_exit(NULL);
iker_martin's avatar
iker_martin committed
274
275
}

276
277
278
279
280
281
282
283
284
285
286
287
288
/*
 * Comprueba si la redistribucion asincrona ha terminado. 
 * Si no ha terminado la funcion termina indicandolo, en caso contrario,
 * se continua con la comunicacion sincrona, el envio de resultados y
 * se desconectan los grupos de procesos.
 *
 * Esta funcion permite dos modos de funcionamiento al comprobar si la
 * comunicacion asincrona ha terminado.
 * Si se utiliza el modo "MAL_USE_NORMAL", se considera terminada cuando
 * los padres terminan de enviar.
 * Si se utiliza el modo "MAL_USE_IBARRIER", se considera terminada cuando
 * los hijos han terminado de recibir.
 */
289
int check_redistribution(int iter, MPI_Request **comm_req) {
290
  int completed, all_completed, test_err;
291
  MPI_Request *req_completed;
iker_martin's avatar
iker_martin committed
292

293
294
  if(config_file->aib == MAL_USE_NORMAL) {
    req_completed = &(*comm_req)[0];
295
  } else { // MAL_USE_IBARRIER
296
    req_completed = &(*comm_req)[1];
iker_martin's avatar
iker_martin committed
297
  }
298
 
299
300
  test_err = MPI_Test(req_completed, &completed, MPI_STATUS_IGNORE);
  if (test_err != MPI_SUCCESS && test_err != MPI_ERR_PENDING) {
301
    printf("P%d aborting -- Test Async\n", group->myId);
302
303
304
305
    MPI_Abort(MPI_COMM_WORLD, test_err);
  }

  MPI_Allreduce(&completed, &all_completed, 1, MPI_INT, MPI_MIN, MPI_COMM_WORLD);
306
  
307
  if(!all_completed) return MAL_ASYNC_PENDING; // Continue only if asynchronous send has ended 
308
  
309
310
311
312

  //MPI_Wait(req_completed, MPI_STATUS_IGNORE);
  if(config_file->aib == MAL_USE_IBARRIER) {
    MPI_Wait(&(*comm_req)[0], MPI_STATUS_IGNORE); // Indicar como completado el envio asincrono
313
314
    //Para la desconexión de ambos grupos de procesos es necesario indicar a MPI que esta 
    //ha terminado, aunque solo se pueda llegar a este punto cuando ha terminado
315
  }
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
  free(*comm_req);
  return end_redistribution(iter);
}


/*
 * Termina la redistribución de los datos con los hijos, comprobando
 * si se han realizado iteraciones con comunicaciones en segundo plano
 * y enviando cuantas iteraciones se han realizado a los hijos.
 *
 * Además se realizan las comunicaciones síncronas se las hay.
 * Finalmente termina enviando los datos temporales a los hijos.
 */ 
int end_redistribution(int iter) {
  int rootBcast = MPI_PROC_NULL;
  if(group->myId == ROOT) rootBcast = MPI_ROOT;

  if(iter > 0) { // Mandar a los hijos iteracion en la que comenzar
    MPI_Bcast(&iter, 1, MPI_INT, rootBcast, group->children);
  }
336
  if(config_file->sdr > 0) { // Realizar envio sincrono
337
      results->sync_start = MPI_Wtime();
338
    send_sync(group->sync_array, config_file->sdr, group->myId, group->numP, ROOT, group->children, group->numS);
339
340
  }

341
  send_results(results, rootBcast, config_file->resizes, group->children);
342
343
344
  // Desconectar intercomunicador con los hijos
  MPI_Comm_disconnect(&(group->children));
  return MAL_COMM_COMPLETED;
iker_martin's avatar
iker_martin committed
345
346
}

347
348
349
350
351
352
/*
 * Inicializacion de los datos de los hijos.
 * En la misma se reciben datos de los padres: La configuracion
 * de la ejecucion a realizar; y los datos a recibir de los padres
 * ya sea de forma sincrona, asincrona o ambas.
 */
iker_martin's avatar
iker_martin committed
353
354
355
356
void Sons_init() {

  // Enviar a los hijos que grupo de procesos son
  MPI_Bcast(&(group->grp), 1, MPI_INT, ROOT, group->parents);
357
  MPI_Bcast(&run_id, 1, MPI_INT, ROOT, group->parents);
iker_martin's avatar
iker_martin committed
358
359
360
361
  group->grp++;

  config_file = recv_config_file(ROOT, group->parents);
  int numP_parents = config_file->procs[group->grp -1];
362
  init_results_data(&results, config_file->resizes - 1, config_file->iters[group->grp]);
iker_martin's avatar
iker_martin committed
363

364
  if(config_file->adr > 0) { // Recibir datos asincronos
365
    recv_sync(&(group->async_array), config_file->adr, group->myId, group->numP, ROOT, group->parents, numP_parents);
366
      results->async_time[group->grp] = MPI_Wtime();
367
368
    MPI_Bcast(&(group->iter_start), 1, MPI_INT, ROOT, group->parents);
  }
369
  if(config_file->sdr > 0) { // Recibir datos sincronos
iker_martin's avatar
iker_martin committed
370
    recv_sync(&(group->sync_array), config_file->sdr, group->myId, group->numP, ROOT, group->parents, numP_parents);
371
    results->sync_time[group->grp] = MPI_Wtime();
iker_martin's avatar
iker_martin committed
372
  }
373
374
375
376
377
378
379
380
381
382
383
384
385

  // Guardar los resultados de esta transmision
  recv_results(results, ROOT, config_file->resizes, group->parents);
  if(config_file->sdr > 0) { // Si no hay datos sincronos, el tiempo es 0
    results->sync_time[group->grp]  = MPI_Wtime() - results->sync_start;
  } else {
    results->sync_time[group->grp]  = 0;
  }
  if(config_file->adr > 0) { // Si no hay datos asincronos, el tiempo es 0
    results->async_time[group->grp]  = MPI_Wtime() - results->async_start;
  } else {
    results->async_time[group->grp]  = 0;
  }
iker_martin's avatar
iker_martin committed
386
387
388
389
390
391
392
393
394
395
396
397
398

  // Desconectar intercomunicador con los hijos
  MPI_Comm_disconnect(&(group->parents));
}


/////////////////////////////////////////
/////////////////////////////////////////
//COMPUTE FUNCTIONS
/////////////////////////////////////////
/////////////////////////////////////////


399
400
/*
 * Simula la ejecucción de una iteración de computo en la aplicación
401
 * que dura al menos un tiempo de "time" segundos.
402
 */
403
void iterate(double *matrix, int n, int async_comm) {
404
  double start_time, actual_time;
iker_martin's avatar
iker_martin committed
405
  double time = config_file->general_time * config_file->factors[group->grp];
406
  double Top = config_file->Top;
407
  int i, operations = 0;
408
  double aux = 0;
409
410

  start_time = actual_time = MPI_Wtime();
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425

  operations = time / Top;
  for(i=0; i < operations; i++) {
    aux += computePiSerial(n);
  }
  actual_time = MPI_Wtime(); // Guardar tiempos
  if(async_comm == MAL_ASYNC_PENDING) { // Se esta realizando una redistribucion de datos asincrona
    operations=0;
  }

  results->iters_time[results->iter_index] = actual_time - start_time;
  results->iters_type[results->iter_index] = operations;
  results->iter_index = results->iter_index + 1;
}
  /*
426
427
  if(async_comm == MAL_ASYNC_PENDING) { // Se esta realizando una redistribucion de datos asincrona
    operations = results->iters_type[config_file->iters[group->grp] - 1];
428
    for (i=0; i<operations; i++) {
429
430
      //computeMatrix(matrix, n);
      computePi(n);
431
    }
432
    actual_time = MPI_Wtime(); // Guardar tiempos
433
434
    operations = 0;

435
  } else { // No hay redistribucion de datos actualmente	  
436
    while (actual_time - start_time < time) {
437
438
      //computeMatrix(matrix, n);
      computePi(n);
439
440
441
      operations++;
      actual_time = MPI_Wtime(); // Guardar tiempos
    }
442
  }
443
  */
444
445
446
447
448

/*
 * Realiza una multiplicación de matrices de tamaño n
 */
void computeMatrix(double *matrix, int n) {
449
450
  int row, col, i;
  double aux;
451

452
453
  for(col=0; i<n; col++) {
    for(row=0; row<n; row++) {
454
455
456
457
458
459
460
461
      aux=0;
      for(i=0; i<n; i++) {
        aux += matrix[row*n + i] * matrix[i*n + col];
      }
    }
  }
}

462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
double computePiSerial(int n) {
    int i;
    double h, sum, x, pi;

    h   = 1.0 / (double) n;  //wide of the rectangle
    sum = 0.0;
    for (i = 0; i < n; i++) {
        x = h * ((double)i + 0.5);   //height of the rectangle
        sum += 4.0 / (1.0 + x*x);
    }

    return pi = h * sum;
    //MPI_Reduce(&sum, &res, 1, MPI_DOUBLE, MPI_SUM, root, MPI_COMM_WORLD);
}



479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
/*
 * Init matrix
 */
void initMatrix(double **matrix, int n) {
  int i, j;

  // Init matrix
  if(matrix != NULL) {
    *matrix = malloc(n * n * sizeof(double));
    if(*matrix == NULL) { MPI_Abort(MPI_COMM_WORLD, -1);}
    for(i=0; i < n; i++) {
      for(j=0; j < n; j++) {
        (*matrix)[i*n + j] = i+j;
      }
    }
  }
}
496
497
498

//======================================================||
//======================================================||
499
//=============INIT/FREE/PRINT FUNCTIONS================||
500
501
502
//======================================================||
//======================================================||

503
504
505
506
/*
 * Muestra datos generales sobre los procesos, su grupo,
 * en que nodo residen y la version de MPI utilizada.
 */
507
508
509
510
511
512
513
514
515
516
517
518
void print_general_info(int myId, int grp, int numP) {
  int len;
  char *name = malloc(MPI_MAX_PROCESSOR_NAME * sizeof(char));
  char *version = malloc(MPI_MAX_LIBRARY_VERSION_STRING * sizeof(char));
  MPI_Get_processor_name(name, &len);
  MPI_Get_library_version(version, &len);
  printf("P%d Nuevo GRUPO %d de %d procs en nodo %s con %s\n", myId, grp, numP, name, version);

  free(name);
  free(version);
}

519
520
521
522
523
524
/*
 * Pide al proceso raiz imprimir los datos sobre las iteraciones realizadas por el grupo de procesos.
 *
 * Si es el ultimo grupo de procesos, muestra los datos obtenidos de tiempo de ejecucion, creacion de procesos
 * y las comunicaciones.
 */
525
int print_final_results() {
iker_martin's avatar
iker_martin committed
526
527
528
  int ptr_local, ptr_global, err;
  char *file_name;

529
  if(group->myId == ROOT) {
iker_martin's avatar
iker_martin committed
530
531
    file_name = NULL;
    file_name = malloc(40 * sizeof(char));
532
    if(file_name == NULL) return -1; // No ha sido posible alojar la memoria
533
    err = snprintf(file_name, 40, "R%d_G%dNP%dID%d.out", run_id, group->grp, group->numP, group->myId);
534
    if(err < 0) return -2; // No ha sido posible obtener el nombre de fichero
iker_martin's avatar
iker_martin committed
535
536
    create_out_file(file_name, &ptr_local, 1);
  
537
538
    print_config_group(config_file, group->grp);
    print_iter_results(results, config_file->iters[group->grp] -1);
iker_martin's avatar
iker_martin committed
539
    free(file_name);
540
541

    if(group->grp == config_file->resizes -1) {
iker_martin's avatar
iker_martin committed
542
543
      file_name = NULL;
      file_name = malloc(20 * sizeof(char));
544
      if(file_name == NULL) return -1; // No ha sido posible alojar la memoria
545
      err = snprintf(file_name, 20, "R%d_Global.out", run_id);
546
      if(err < 0) return -2; // No ha sido posible obtener el nombre de fichero
iker_martin's avatar
iker_martin committed
547
548

      create_out_file(file_name, &ptr_global, 1);
549
550
      print_config(config_file, group->grp);
      print_global_results(results, config_file->resizes);
iker_martin's avatar
iker_martin committed
551
552
      free(file_name);
      
553
554
    }
  }
555
  return 0;
556
557
558
559
560
}

/*
 * Inicializa la estructura group
 */
561
void init_group_struct(char *argv[], int argc, int myId, int numP) {
562
563
564
565
566
  group = malloc(1 * sizeof(group_data));
  group->myId        = myId;
  group->numP        = numP;
  group->grp         = 0;
  group->iter_start  = 0;
567
  group->commAsync   = MAL_COMM_UNINITIALIZED;
568
  group->argc        = argc;
569
570
  group->argv        = argv;
}
571

572
573
574
575
576
577
578
579
580
581
/*
 * Inicializa los datos para este grupo de procesos.
 *
 * En caso de ser el primer grupo de procesos, lee el fichero de configuracion
 * e inicializa los vectores de comunicacion.
 *
 * En caso de ser otro grupo de procesos entra a la funcion "Sons_init()" donde
 * se comunican con los padres para inicializar sus datos.
 */
void init_application() {
582
583
584
585
586
587
588
  if(group->argc < 2) {
    printf("Falta el fichero de configuracion. Uso:\n./programa config.ini id\nEl argumento numerico id es opcional\n");
    exit(0);
  }
  if(group->argc > 2) {
    run_id = atoi(group->argv[2]);
  }
589

590
591
592
593
594
595
596
597
  config_file = read_ini_file(group->argv[1]);
  init_results_data(&results, config_file->resizes, config_file->iters[group->grp]);
  if(config_file->sdr > 0) {
    malloc_comm_array(&(group->sync_array), config_file->sdr , group->myId, group->numP);
  }
  if(config_file->adr > 0) {
    malloc_comm_array(&(group->async_array), config_file->adr , group->myId, group->numP);
  }
598
599

    
600
601
602
603
604
  double result, start_time = MPI_Wtime();
  int i;
  result = 0;
  for(i=0; i<20000; i++) {
    result += computePiSerial(config_file->matrix_tam);
605
  }
606
607
608
609
610
  printf("Creado Top con valor %lf\n", result);
  fflush(stdout);

  config_file->Top = (MPI_Wtime() - start_time) / 20000; //Tiempo de una iteracion
  MPI_Bcast(&(config_file->Top), 1, MPI_DOUBLE, ROOT, MPI_COMM_WORLD);
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
}

/*
 * Libera toda la memoria asociada con la aplicacion
 */
void free_application_data() {
  if(config_file->sdr > 0) {
    free(group->sync_array);
  }
  if(config_file->adr > 0) {
    free(group->async_array);
  }
  free(group);
  free_config(config_file);
  free_results_data(&results);
}
iker_martin's avatar
iker_martin committed
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651


/* 
 * Función para crear un fichero con el nombre pasado como argumento.
 * Si el nombre ya existe, se escribe la informacion a continuacion.
 *
 * El proceso que llama a la función pasa a tener como salida estandar
 * dicho fichero si el valor "newstdout" es verdadero.
 *
 */
int create_out_file(char *nombre, int *ptr, int newstdout) {
  int err;

  *ptr = open(nombre, O_WRONLY | O_CREAT | O_APPEND, 0644);
  if(*ptr < 0) return -1; // No ha sido posible crear el fichero

  if(newstdout) {
    err = close(1);
    if(err < 0) return -2; // No es posible modificar la salida estandar
    err = dup(*ptr);
    if(err < 0) return -3; // No es posible modificar la salida estandar
  }

  return 0;
}