Files
pytorch/c10/test/util/Semaphore_test.cpp
dolpm 66f53889d5 [nativert] port semaphore to c10 util (#153504)
Summary:
nativert RFC: https://github.com/zhxchen17/rfcs/blob/master/RFC-0043-torch-native-runtime.md

To land the runtime into PyTorch core, we will gradually land logical parts of the code into the Github issue and get each piece properly reviewed.

This diff adds a simple semaphore interface into c10 until c++20 where we get counting_semaphore

gonna need a oss build export to take a look at this...

Test Plan: CI

Differential Revision: D73882656

Pull Request resolved: https://github.com/pytorch/pytorch/pull/153504
Approved by: https://github.com/zhxchen17
2025-05-28 19:17:30 +00:00

36 lines
906 B
C++

#include <c10/util/Semaphore.h>
#include <c10/util/irange.h>
#include <gtest/gtest.h>
#include <thread>
using namespace ::testing;
TEST(SemaphoreTest, TestConcurrency) {
auto num_threads = std::thread::hardware_concurrency();
auto num_incr = 10000;
c10::Semaphore sem;
std::vector<std::thread> threads;
for ([[maybe_unused]] const auto _ : c10::irange(num_threads)) {
threads.emplace_back([num_incr = num_incr, &sem]() {
for ([[maybe_unused]] const auto _ : c10::irange(num_incr)) {
sem.release();
}
for ([[maybe_unused]] const auto _ : c10::irange(num_incr)) {
sem.acquire();
}
sem.release(num_incr);
for ([[maybe_unused]] const auto _ : c10::irange(num_incr)) {
sem.acquire();
}
});
}
std::for_each(
threads.begin(), threads.end(), [](std::thread& t) { t.join(); });
EXPECT_FALSE(sem.tryAcquire());
}