From edd523ffcb39c1c57944796fabfc71c70a10ce2e Mon Sep 17 00:00:00 2001 From: Mole Shang <135e2@135e2.dev> Date: Fri, 16 Feb 2024 11:29:36 +0800 Subject: lab thread: finish --- notxv6/barrier.c | 16 ++++++++++++---- notxv6/ph.c | 9 ++++++--- 2 files changed, 18 insertions(+), 7 deletions(-) (limited to 'notxv6') diff --git a/notxv6/barrier.c b/notxv6/barrier.c index 12793e8..b7737a6 100644 --- a/notxv6/barrier.c +++ b/notxv6/barrier.c @@ -25,12 +25,20 @@ barrier_init(void) static void barrier() { - // YOUR CODE HERE - // // Block until all threads have called barrier() and // then increment bstate.round. - // - + pthread_mutex_lock(&bstate.barrier_mutex); + bstate.nthread++; + if(bstate.nthread != nthread) { + pthread_cond_wait(&bstate.barrier_cond, &bstate.barrier_mutex); + } else { + pthread_cond_broadcast(&bstate.barrier_cond); + // All threads have reached barrier. + // reset and increase round + bstate.nthread = 0; + bstate.round++; + } + pthread_mutex_unlock(&bstate.barrier_mutex); } static void * diff --git a/notxv6/ph.c b/notxv6/ph.c index 82afe76..db8a630 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() @@ -47,6 +47,7 @@ void put(int key, int value) if (e->key == key) break; } + pthread_mutex_lock(&lock[i]); if(e){ // update the existing key. e->value = value; @@ -54,7 +55,7 @@ void put(int key, int value) // the new is new. insert(key, value, &table[i], table[i]); } - + pthread_mutex_unlock(&lock[i]); } static struct entry* @@ -67,7 +68,6 @@ get(int key) for (e = table[i]; e != 0; e = e->next) { if (e->key == key) break; } - return e; } @@ -113,6 +113,9 @@ main(int argc, char *argv[]) nthread = atoi(argv[1]); tha = malloc(sizeof(pthread_t) * nthread); srandom(0); + for (int i = 0; i < NBUCKET; i++) { + pthread_mutex_init(&lock[i], NULL); + } assert(NKEYS % nthread == 0); for (int i = 0; i < NKEYS; i++) { keys[i] = random(); -- cgit v1.2.3