From b6c3b4236131aab1e1c2fa8b85a67e2dbce6ceb2 Mon Sep 17 00:00:00 2001 From: Denis Monnerat Date: Thu, 9 Oct 2025 15:58:39 +0200 Subject: [PATCH] coorection td6 --- tp/tp6/correc_gr34/ex1.c | 30 ++++++++++++++++++++ tp/tp6/correc_gr34/sum.c | 60 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 90 insertions(+) create mode 100644 tp/tp6/correc_gr34/ex1.c create mode 100644 tp/tp6/correc_gr34/sum.c diff --git a/tp/tp6/correc_gr34/ex1.c b/tp/tp6/correc_gr34/ex1.c new file mode 100644 index 0000000..412cf07 --- /dev/null +++ b/tp/tp6/correc_gr34/ex1.c @@ -0,0 +1,30 @@ +#include +#include +#include +#include + +#define NUM_THREADS 16 + +void *thread(void *thread_id) { + long id = ((long ) thread_id); + printf("Hello from thread %ld\n", id); + + return (void*)(2*id); +} + +int main() { + pthread_t threads[NUM_THREADS]; + int t[NUM_THREADS]; + long res; + for (long i = 0; i < NUM_THREADS; i++){ +// t[i] = i; + assert( pthread_create(&threads[i], NULL, thread, (void*)i) == 0); + } + + for (int i = 0; i < NUM_THREADS; i++){ + assert( pthread_join(threads[i],(void *)&res) == 0); + printf("%ld\n",res); + } + + return EXIT_SUCCESS; +} diff --git a/tp/tp6/correc_gr34/sum.c b/tp/tp6/correc_gr34/sum.c new file mode 100644 index 0000000..9bfb6ed --- /dev/null +++ b/tp/tp6/correc_gr34/sum.c @@ -0,0 +1,60 @@ +#include +#include +#include +#include + +static inline double tstamp(void) +{ + struct timespec tv; + clock_gettime(CLOCK_MONOTONIC, &tv); + return tv.tv_sec + tv.tv_nsec * 1.0e-9; +} +typedef struct arg { + long start; + long end; + long step; + long S; +} arg; + +void* slice(void* a) { + long start = ((arg*)a)->start; + long end = ((arg*)a)->end; + long step= ((arg*)a)->step; + long S = 0; + for(long i = start; i <= end; i += step) + S += i; + ((arg*)a)->S = S; + return NULL; + //return (void*)S; + +} + +int main(int argc, char *argv[]) +{ + long N = strtol(argv[1], NULL,0); + long M = strtol(argv[2], NULL,0); + long S = 0, ret; + double t1,t2; + pthread_t* threads = (pthread_t*)calloc(M,sizeof(pthread_t)); + arg* args = (arg*)calloc(M,sizeof(arg)); + t1 = tstamp(); + for (long i = 0; i < M; i++){ + + args[i].start = i + 1; + args[i].end = N; + args[i].step = M; + + assert( pthread_create(&threads[i], NULL, slice, (void*)(args + i)) == 0); + } + + for (int i = 0; i < M; i++){ + // assert( pthread_join(threads[i], (void*)&ret) == 0); + assert( pthread_join(threads[i], NULL) == 0); + S += args[i].S; + } + t2 = tstamp(); + assert( S == N*(N+1)/2 ); + printf("S = %ld time = %lf\n",S,t2 - t1); + + return EXIT_SUCCESS; +}