summaryrefslogtreecommitdiff
path: root/Year_3
diff options
context:
space:
mode:
authorSanto Cariotti <santo@dcariotti.me>2021-11-24 22:21:27 +0100
committerSanto Cariotti <santo@dcariotti.me>2021-11-24 22:21:27 +0100
commit12eb2dc3d43e0a24e7713e1f470587ba97f3f2a0 (patch)
tree285c95d5d7f8445e352748395f9f1552aff4c571 /Year_3
parent7307ddd09c9d139162802b8ce9672a0a3466b4e3 (diff)
tsdwl: add exam
Diffstat (limited to 'Year_3')
-rw-r--r--Year_3/TSDWL/ex_20170203/thread.c81
1 files changed, 81 insertions, 0 deletions
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 <stdio.h>
+#include <stdlib.h>
+#include <pthread.h>
+#include <time.h>
+#include <unistd.h>
+
+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;
+}