diff options
author | Santo Cariotti <santo@dcariotti.me> | 2021-12-01 12:36:35 +0100 |
---|---|---|
committer | Santo Cariotti <santo@dcariotti.me> | 2021-12-01 12:36:35 +0100 |
commit | 071a8ee7b742498dc4714d06eaf55f6a40aeb7fa (patch) | |
tree | 7884e81d238cfa69d8230f2132cfce4271e2f5f4 /Year_3/TSDWL/ex_unk1 | |
parent | a44b9ed57ffebfa5b13b29e94c7da97bed99911b (diff) |
tsdwl: add exam
Diffstat (limited to 'Year_3/TSDWL/ex_unk1')
-rw-r--r-- | Year_3/TSDWL/ex_unk1/thread.c | 55 |
1 files changed, 55 insertions, 0 deletions
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 <stdio.h> +#include <stdlib.h> +#include <time.h> +#include <pthread.h> +#include <unistd.h> +#include <string.h> + +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; +} |