From 87470490676ee6dc087e3ebe2a3ce3cfbd4afbd9 Mon Sep 17 00:00:00 2001 From: Sanjit Bhat Date: Wed, 13 Sep 2023 02:01:38 -0400 Subject: release lab thread --- notxv6/barrier.c | 78 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 notxv6/barrier.c (limited to 'notxv6/barrier.c') diff --git a/notxv6/barrier.c b/notxv6/barrier.c new file mode 100644 index 0000000..12793e8 --- /dev/null +++ b/notxv6/barrier.c @@ -0,0 +1,78 @@ +#include +#include +#include +#include +#include + +static int nthread = 1; +static int round = 0; + +struct barrier { + pthread_mutex_t barrier_mutex; + pthread_cond_t barrier_cond; + int nthread; // Number of threads that have reached this round of the barrier + int round; // Barrier round +} bstate; + +static void +barrier_init(void) +{ + assert(pthread_mutex_init(&bstate.barrier_mutex, NULL) == 0); + assert(pthread_cond_init(&bstate.barrier_cond, NULL) == 0); + bstate.nthread = 0; +} + +static void +barrier() +{ + // YOUR CODE HERE + // + // Block until all threads have called barrier() and + // then increment bstate.round. + // + +} + +static void * +thread(void *xa) +{ + long n = (long) xa; + long delay; + int i; + + for (i = 0; i < 20000; i++) { + int t = bstate.round; + assert (i == t); + barrier(); + usleep(random() % 100); + } + + return 0; +} + +int +main(int argc, char *argv[]) +{ + pthread_t *tha; + void *value; + long i; + double t1, t0; + + if (argc < 2) { + fprintf(stderr, "%s: %s nthread\n", argv[0], argv[0]); + exit(-1); + } + nthread = atoi(argv[1]); + tha = malloc(sizeof(pthread_t) * nthread); + srandom(0); + + barrier_init(); + + for(i = 0; i < nthread; i++) { + assert(pthread_create(&tha[i], NULL, thread, (void *) i) == 0); + } + for(i = 0; i < nthread; i++) { + assert(pthread_join(tha[i], &value) == 0); + } + printf("OK; passed\n"); +} -- cgit v1.2.3 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 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) (limited to 'notxv6/barrier.c') 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 * -- cgit v1.2.3