summaryrefslogtreecommitdiff
path: root/notxv6/barrier.c
diff options
context:
space:
mode:
authorMole Shang <[email protected]>2024-02-19 14:10:32 +0800
committerMole Shang <[email protected]>2024-02-19 14:36:21 +0800
commitd86118fc80267649b4791c8c0c72ebd60edf1ef2 (patch)
treeb792b617b4df80a5803a9c1164d0e3fdfe9cfe31 /notxv6/barrier.c
parentb20ef9d0210fd7d9403acde1857eed1b9880c0b2 (diff)
parent0cf897cbe05fd8485162619db4244f4159d0eb52 (diff)
downloadxv6-labs-d86118fc80267649b4791c8c0c72ebd60edf1ef2.tar.gz
xv6-labs-d86118fc80267649b4791c8c0c72ebd60edf1ef2.tar.bz2
xv6-labs-d86118fc80267649b4791c8c0c72ebd60edf1ef2.zip
Merge branch 'fs' into mmap
Conflicts: .gitignore Makefile conf/lab.mk kernel/defs.h user/user.h
Diffstat (limited to 'notxv6/barrier.c')
-rw-r--r--notxv6/barrier.c86
1 files changed, 86 insertions, 0 deletions
diff --git a/notxv6/barrier.c b/notxv6/barrier.c
new file mode 100644
index 0000000..b7737a6
--- /dev/null
+++ b/notxv6/barrier.c
@@ -0,0 +1,86 @@
+#include <stdlib.h>
+#include <unistd.h>
+#include <stdio.h>
+#include <assert.h>
+#include <pthread.h>
+
+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()
+{
+ // 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 *
+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");
+}