From 7307ddd09c9d139162802b8ce9672a0a3466b4e3 Mon Sep 17 00:00:00 2001 From: Santo Cariotti Date: Wed, 24 Nov 2021 21:59:49 +0100 Subject: tsdwl: add exam --- Year_3/TSDWL/ex_20170201/thread.c | 59 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 Year_3/TSDWL/ex_20170201/thread.c diff --git a/Year_3/TSDWL/ex_20170201/thread.c b/Year_3/TSDWL/ex_20170201/thread.c new file mode 100644 index 0000000..34ba440 --- /dev/null +++ b/Year_3/TSDWL/ex_20170201/thread.c @@ -0,0 +1,59 @@ +#include +#include +#include +#include +#include + +pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; +int sample = 50; + +void* +fn(void* arg) +{ + char* th = (char*) arg; + int new_sample; + + char indent[3] = ""; + if (strcmp(th, "B") == 0) + strcpy(indent, "\t"); + else if (strcmp(th, "C") == 0) + strcpy(indent, "\t\t"); + + while (1) { + new_sample = (rand() % 81) + 10; + pthread_mutex_lock(&mutex); + + printf("%sSono il thread %s: sample valeva %d, adesso vale %d\n", indent, th, sample, new_sample); + if (sample != new_sample) { + sample = new_sample; + pthread_mutex_unlock(&mutex); + } else { + pthread_mutex_unlock(&mutex); + break; + } + + } + + printf("%sSono il thread %s, e sto uscendo!\n", indent, th); + + pthread_exit(NULL); +} + +int +main() +{ + pthread_t th[3]; + srand(time(NULL)); + + pthread_create(&th[0], NULL, &fn, (void*) "A"); + pthread_create(&th[1], NULL, &fn, (void*) "B"); + pthread_create(&th[2], NULL, &fn, (void*) "C"); + + pthread_join(th[0], NULL); + pthread_join(th[1], NULL); + pthread_join(th[2], NULL); + + printf("Il valore finale di sample e' %d\n", sample); + + return 0; +} -- cgit v1.2.3-18-g5258