From 071a8ee7b742498dc4714d06eaf55f6a40aeb7fa Mon Sep 17 00:00:00 2001 From: Santo Cariotti Date: Wed, 1 Dec 2021 12:36:35 +0100 Subject: tsdwl: add exam --- Year_3/TSDWL/ex_unk1/thread.c | 55 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 Year_3/TSDWL/ex_unk1/thread.c diff --git a/Year_3/TSDWL/ex_unk1/thread.c b/Year_3/TSDWL/ex_unk1/thread.c new file mode 100644 index 0000000..8fdefc9 --- /dev/null +++ b/Year_3/TSDWL/ex_unk1/thread.c @@ -0,0 +1,55 @@ +#include +#include +#include +#include +#include +#include + +int x = 0; +pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; + +void* +fn(void* arg) +{ + char* thread_name = (char*) arg; + int xrand; + long hit; + + hit = 0; + while (1) { + xrand = rand() % 1000; + usleep(xrand); + + pthread_mutex_lock(&mutex); + if (x > 500) { + printf("I'm the thread %s with hit = '%ld' and x = '%d'\n", thread_name, hit, x); + pthread_mutex_unlock(&mutex); + break; + } + x++; + pthread_mutex_unlock(&mutex); + + hit++; + } + + pthread_exit((void*) hit); +} + +int +main() +{ + pthread_t tA, tB; + void *result1, *result2; + long total; + srand(time(NULL)); + + pthread_create(&tA, NULL, &fn, (void*) "A"); + pthread_create(&tB, NULL, &fn, (void*) "B"); + + pthread_join(tA, &result1); + pthread_join(tB, &result2); + + total = (long) result1 + (long) result2; + printf("Total = %ld + %ld = %ld'\n", (long) result1, (long) result2, total); + return 0; +} -- cgit v1.2.3-18-g5258