[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,117 @@
+//===-- Tests for pthread_barrier_t ---------------------------------------===//
+//
+// 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/pthread/pthread_barrier_destroy.h"
+#include "src/pthread/pthread_barrier_init.h"
+#include "src/pthread/pthread_barrier_wait.h"
+
+#include "src/__support/CPP/atomic.h"
+#include "src/pthread/pthread_create.h"
+#include "src/pthread/pthread_join.h"
+#include "src/pthread/pthread_mutex_destroy.h"
+#include "src/pthread/pthread_mutex_init.h"
+#include "src/pthread/pthread_mutex_lock.h"
+#include "src/pthread/pthread_mutex_unlock.h"
+#include "src/stdio/printf.h"
+
+#include "test/IntegrationTest/test.h"
+
+#include <pthread.h>
+
+pthread_barrier_t barrier;
+
+void smoke_test() {
+  ASSERT_EQ(LIBC_NAMESPACE::pthread_barrier_init(&barrier, nullptr, 1), 0);
+  ASSERT_EQ(LIBC_NAMESPACE::pthread_barrier_wait(&barrier),
+            PTHREAD_BARRIER_SERIAL_THREAD);
+  ASSERT_EQ(LIBC_NAMESPACE::pthread_barrier_destroy(&barrier), 0);
+}
+
+LIBC_NAMESPACE::cpp::Atomic<int> counter;
+void *increment_counter_and_wait(void *args) {
+  counter.fetch_add(1);
+  LIBC_NAMESPACE::pthread_barrier_wait(&barrier);
+  return 0;
+}
+
+void single_use_barrier() {
+  counter.set(0);
+  const int NUM_THREADS = 30;
----------------
brooksmoses wrote:

There could be edge cases in the case with exactly 1 thread. I think it would be good to make the thread count a parameter of this function (and the other functions), and call it once with 1 and once with a larger number.

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


More information about the libc-commits mailing list