uthread/tst/52-dac-sum.c
2025-04-18 19:52:55 +02:00

90 lines
2.2 KiB
C

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <stdlib.h>
#include <sys/time.h>
#include "thread.h"
/* Somme divide and conquer
*
* la durée doit être proportionnel à la valeur du résultat.
* valgrind doit être content.
* jusqu'à quelle valeur cela fonctionne-t-il ?
*
* support nécessaire:
* - thread_create()
* - thread_join() avec récupération de la valeur de retour
* - retour sans thread_exit()
*/
struct dac_in_t {
unsigned long* arr;
int st;
int end;
};
static void* s_dac_sum(void* _value)
{
thread_t th, th2;
int err;
void *res = NULL, *res2 = NULL;
struct dac_in_t* in = (struct dac_in_t*) _value;
/* on passe un peu la main aux autres pour eviter de faire uniquement la partie gauche de l'arbre */
thread_yield();
if (in->end <= in->st + 1)
return (void*)in->arr[in->st];
size_t mid = (in->end + in->st) / 2;
struct dac_in_t in1 = {in->arr, in->st, mid};
struct dac_in_t in2 = {in->arr, mid, in->end};
err = thread_create(&th, s_dac_sum, (void*)&in1);
assert(!err);
err = thread_create(&th2, s_dac_sum, (void*)&in2);
assert(!err);
err = thread_join(th, &res);
assert(!err);
err = thread_join(th2, &res2);
assert(!err);
return (void*)((unsigned long) res + (unsigned long) res2);
}
int main(int argc, char *argv[])
{
unsigned long res;
size_t n;
struct timeval tv1, tv2;
double s;
if (argc < 2) {
printf("argument manquant: entier n pour lequel dac_sum(n)\n");
return EXIT_FAILURE;
}
n = atoi(argv[1]);
unsigned long arr[n];
for (size_t i = 0 ; i < n ; ++i)
arr[i] = i + 1;
struct dac_in_t in = { arr, .st=0, .end=n };
gettimeofday(&tv1, NULL);
res = (unsigned long)s_dac_sum((void *)&in);
gettimeofday(&tv2, NULL);
s = (tv2.tv_sec-tv1.tv_sec) + (tv2.tv_usec-tv1.tv_usec) * 1e-6;
unsigned long expected = (n * (n + 1)) / 2;
if (res != expected) {
printf("dac(%lu) != %lu (FAILED)\n", res, expected);
printf("GRAPH;%lu;%lu;%e;%s\n", n, res, s, "FAILED" );
return EXIT_FAILURE;
} else {
printf("fibo(%lu) = %lu en %e s\n", n, res, s );
printf("GRAPH;%lu;%lu;%e;%s\n", n, res, s, "SUCCESS" );
return EXIT_SUCCESS;
}
}