summaryrefslogtreecommitdiff
path: root/Year_3
diff options
context:
space:
mode:
authorSanto Cariotti <santo@dcariotti.me>2021-11-23 21:33:09 +0100
committerSanto Cariotti <santo@dcariotti.me>2021-11-23 21:33:12 +0100
commit0183ce2e23134bd1805d481daa56d174865f7cb9 (patch)
treec9fb2d664b611256ffdd038b66324fbcec06e046 /Year_3
parent14f0ae5e5b68c78cef56e80d630d1a4611a2835f (diff)
tsdwl: add exam (thread blocks (?) )
Diffstat (limited to 'Year_3')
-rw-r--r--Year_3/TSDWL/ex_20131219/thread.c67
1 files changed, 67 insertions, 0 deletions
diff --git a/Year_3/TSDWL/ex_20131219/thread.c b/Year_3/TSDWL/ex_20131219/thread.c
new file mode 100644
index 0000000..e46d05b
--- /dev/null
+++ b/Year_3/TSDWL/ex_20131219/thread.c
@@ -0,0 +1,67 @@
+#include <pthread.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <time.h>
+
+int m;
+pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
+pthread_cond_t cond;
+
+void*
+fn_t1(void* arg)
+{
+ int xrand;
+
+ while (1) {
+ pthread_mutex_lock(&mutex);
+ if (m >= 1 && m <= 5) {
+ xrand = (rand() % 10) + 1;
+ printf("Thread 1: (%d, %d)\n", m, xrand);
+ m = xrand;
+ pthread_cond_broadcast(&cond);
+ pthread_mutex_unlock(&mutex);
+ } else {
+ pthread_mutex_unlock(&mutex);
+ pthread_cond_wait(&cond, &mutex);
+ }
+ }
+
+ pthread_exit(NULL);
+}
+
+void*
+fn_t2(void* arg)
+{
+ int xrand;
+
+ while (1) {
+ pthread_mutex_lock(&mutex);
+ if (m >= 6 && m <= 10) {
+ xrand = (rand() % 10) + 1;
+ printf("Thread 2: (%d, %d)\n", m, xrand);
+ m = xrand;
+ pthread_cond_broadcast(&cond);
+ pthread_mutex_unlock(&mutex);
+ } else {
+ pthread_mutex_unlock(&mutex);
+ pthread_cond_wait(&cond, &mutex);
+ }
+ }
+
+ pthread_exit(NULL);
+}
+
+int
+main()
+{
+ pthread_t th[2];
+ srand(time(NULL));
+ m = (rand() % 10) + 1;
+
+ pthread_create(&th[0], NULL, (void*)&fn_t1, NULL);
+ pthread_create(&th[1], NULL, (void*)&fn_t2, NULL);
+ pthread_join(th[0], NULL);
+ pthread_join(th[1], NULL);
+
+ return 0;
+}