mirror of
https://github.com/pytorch/pytorch.git
synced 2025-10-22 14:15:01 +08:00
Summary: Pull Request resolved: https://github.com/pytorch/pytorch/pull/74110 Since this class was added, it's missing a unit test. dbort first noticed it, so adding one in this commit. ghstack-source-id: 151471746 Test Plan: `buck test //xplat/caffe2/c10:c10_test` Reviewed By: dbort Differential Revision: D34822911 fbshipit-source-id: 919a125081a2093d6f4e5a2cdb008145c05ec803 (cherry picked from commit 358b7dacced866c54b8c1972393d042ebbd93d9e)
44 lines
939 B
C++
44 lines
939 B
C++
#include <c10/util/Synchronized.h>
|
|
#include <gtest/gtest.h>
|
|
|
|
#include <array>
|
|
#include <thread>
|
|
|
|
namespace {
|
|
|
|
TEST(Synchronized, TestSingleThreadExecution) {
|
|
c10::Synchronized<int> iv(0);
|
|
const int kMaxValue = 100;
|
|
for (int i = 0; i < kMaxValue; ++i) {
|
|
auto ret = iv.withLock([](int& iv) { return ++iv; });
|
|
EXPECT_EQ(ret, i + 1);
|
|
}
|
|
|
|
iv.withLock([kMaxValue](int& iv) { EXPECT_EQ(iv, kMaxValue); });
|
|
}
|
|
|
|
TEST(Synchronized, TestMultiThreadedExecution) {
|
|
c10::Synchronized<int> iv(0);
|
|
#define NUM_LOOP_INCREMENTS 10000
|
|
|
|
auto thread_cb = [&iv]() {
|
|
for (int i = 0; i < NUM_LOOP_INCREMENTS; ++i) {
|
|
iv.withLock([](int& iv) { ++iv; });
|
|
}
|
|
};
|
|
|
|
std::array<std::thread, 10> threads;
|
|
for (auto& t : threads) {
|
|
t = std::thread(thread_cb);
|
|
}
|
|
|
|
for (auto& t : threads) {
|
|
t.join();
|
|
}
|
|
|
|
iv.withLock([](int& iv) { EXPECT_EQ(iv, NUM_LOOP_INCREMENTS * 10); });
|
|
#undef NUM_LOOP_INCREMENTS
|
|
}
|
|
|
|
} // namespace
|