From 2c76ba809199168a45ae05cca265635fdee6cf3d Mon Sep 17 00:00:00 2001 From: ridethepig Date: Wed, 1 Feb 2023 14:53:46 +0000 Subject: [PATCH] ph ok,though nothing interesting --- answers-thread.txt | 12 ++++++++++++ notxv6/ph.c | 11 ++++++++--- 2 files changed, 20 insertions(+), 3 deletions(-) create mode 100644 answers-thread.txt diff --git a/answers-thread.txt b/answers-thread.txt new file mode 100644 index 0000000..0b3ab09 --- /dev/null +++ b/answers-thread.txt @@ -0,0 +1,12 @@ +Q: Why are there missing keys with 2 threads, but not with 1 thread? Identify a sequence of events with 2 threads that can lead to a key being missing. +A: Suppose K1 % NBUCKET === K2 % NBUCKET = i0 + T1 put(K1); + T2 put(K2); + T1 not found + T2 not found + T1 insert(K1, V1, &table[i0], table[i0]) + T2 insert(K2, V2, &table[i0], table[i0]) + T1 malloc e1, e1->key = K1, e1->value = V1, e1->next = table[i0] + T2 malloc e2, e2->key = K2, e2->value = V2, e2->next = table[i0] + T1 *(&table[i0]) = e1 + T2 *(&table[i0]) = e2 <---- K1 lost diff --git a/notxv6/ph.c b/notxv6/ph.c index 82afe76..566344f 100644 --- a/notxv6/ph.c +++ b/notxv6/ph.c @@ -16,7 +16,7 @@ struct entry { struct entry *table[NBUCKET]; int keys[NKEYS]; int nthread = 1; - +pthread_mutex_t lock[NBUCKET]; double now() @@ -43,6 +43,7 @@ void put(int key, int value) // is the key already present? struct entry *e = 0; + pthread_mutex_lock(&lock[i]); for (e = table[i]; e != 0; e = e->next) { if (e->key == key) break; @@ -54,6 +55,7 @@ void put(int key, int value) // the new is new. insert(key, value, &table[i], table[i]); } + pthread_mutex_unlock(&lock[i]); } @@ -64,10 +66,11 @@ get(int key) struct entry *e = 0; + pthread_mutex_lock(&lock[i]); for (e = table[i]; e != 0; e = e->next) { if (e->key == key) break; } - + pthread_mutex_unlock(&lock[i]); return e; } @@ -117,7 +120,9 @@ main(int argc, char *argv[]) for (int i = 0; i < NKEYS; i++) { keys[i] = random(); } - + for (int i = 0; i < NBUCKET; i ++){ + pthread_mutex_init(&lock[i], NULL); + } // // first the puts //