[libc-commits] [libc] [libc] Implement barriers for pthreads (PR #148948)

Brooks Moses via libc-commits libc-commits at lists.llvm.org
Thu Jul 17 12:47:19 PDT 2025


================
@@ -0,0 +1,83 @@
+//===-- Implementation of Barrier class ------------- ---------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#include "src/__support/threads/barrier.h"
+#include "barrier.h"
+#include "hdr/errno_macros.h"
+#include "src/__support/threads/mutex.h"
+
+namespace LIBC_NAMESPACE_DECL {
+
+const int BARRIER_FIRST_EXITED = -1;
+
+int Barrier::init(Barrier *b,
+                  const pthread_barrierattr_t *attr __attribute__((unused)),
+                  unsigned count) {
+  LIBC_ASSERT(attr == nullptr); // TODO implement barrierattr
+  if (count == 0)
+    return EINVAL;
+
+  b->expected = count;
+  b->waiting = 0;
+  b->blocking = true;
+
+  int err;
+  err = CndVar::init(&b->entering);
+  if (err != 0)
+    return err;
+
+  err = CndVar::init(&b->exiting);
+  if (err != 0)
+    return err;
+
+  Mutex::init(&b->m, false, false, false, false);
+  return 0;
+}
+
+int Barrier::wait() {
+  m.lock();
+
+  // if the barrier is emptying out threads, wait until it finishes
+  while (!blocking) {
+    entering.wait(&m);
+  }
+  waiting++;
+
+  if (waiting == expected) {
+    // this is the last thread to call wait(), so lets wake everyone up
+    blocking = false;
+    exiting.broadcast();
+  } else {
+    // block threads until waiting = expected
+    while (blocking) {
+      exiting.wait(&m);
+    }
+  }
+  waiting--;
+
+  // all threads have exited the barrier, lets let the ones waiting to enter
+  // continue
----------------
brooksmoses wrote:

Here you have the condition-explaining comment before the `if`, but above you have the comments within the `if`.  This should be consistent.

Also, this should be "let's", and the comment should probably mention why `BARRIER_FIRST_EXITED` is being set for this condition.  (Something like "Posix expects the return value to be `PTHREAD_BARRIER_SERIAL_THREAD` for exactly one arbitrary thread in the set, so it might as well be this one," perhaps?)

https://github.com/llvm/llvm-project/pull/148948


More information about the libc-commits mailing list