From 12eb2dc3d43e0a24e7713e1f470587ba97f3f2a0 Mon Sep 17 00:00:00 2001 From: Santo Cariotti Date: Wed, 24 Nov 2021 22:21:27 +0100 Subject: tsdwl: add exam --- Year_3/TSDWL/ex_20170203/thread.c | 81 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 81 insertions(+) create mode 100644 Year_3/TSDWL/ex_20170203/thread.c (limited to 'Year_3/TSDWL') diff --git a/Year_3/TSDWL/ex_20170203/thread.c b/Year_3/TSDWL/ex_20170203/thread.c new file mode 100644 index 0000000..3471f88 --- /dev/null +++ b/Year_3/TSDWL/ex_20170203/thread.c @@ -0,0 +1,81 @@ +#include +#include +#include +#include +#include + +int n; +pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; + +void* +fnO(void* arg) +{ + int xrand; + int count = 0; + + while (1) { + usleep(200 * 1000); + do { + xrand = rand(); + } while ((xrand % 2) == 1); + + count++; + pthread_mutex_lock(&mutex); + printf("Thread O, count = %d, old x = %d, x = %d, even = %d\n", count, n, n+xrand, ((n+xrand) % 2)==0); + n += xrand; + + if ((count == 1000) || (count >= 10 && (n%2) == 0)) { + pthread_mutex_unlock(&mutex); + break; + } + pthread_mutex_unlock(&mutex); + + } + + printf("Thread O terminated.\n"); + pthread_exit(NULL); +} + +void* +fnE(void* arg) +{ + int xrand; + int count = 0; + + while (1) { + usleep(200 * 1000); + do { + xrand = rand(); + } while ((xrand % 2) == 0); + + count++; + pthread_mutex_lock(&mutex); + printf("\tThread E, count = %d, old x = %d, x = %d, odd = %d\n", count, n, n+xrand, ((n+xrand) % 2)==1); + n += xrand; + + if ((count == 1000) || (count >= 10 && (n%2) == 1)) { + pthread_mutex_unlock(&mutex); + break; + } + pthread_mutex_unlock(&mutex); + } + + printf("\tThread E terminated.\n"); + pthread_exit(NULL); +} + +int +main() +{ + pthread_t tO, tE; + srand(time(NULL)); + n = 0; + + pthread_create(&tO, NULL, &fnO, NULL); + pthread_create(&tE, NULL, &fnE, NULL); + + pthread_join(tO, NULL); + pthread_join(tE, NULL); + + return 0; +} -- cgit v1.2.3-18-g5258