Files
swift-mirror/unittests/Threading/Once.cpp
Alastair Houghton 4280222286 [Unittests] Add more threading library tests.
Added explicit tests for `swift::once` and also for the ulock implementation
used on Linux.

rdar://90776105
2022-05-24 14:57:39 +01:00

67 lines
1.8 KiB
C++

//===--- Once.cpp - Tests the swift::once() implementation ----------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#include "swift/Threading/Once.h"
#include "gtest/gtest.h"
#include "ThreadingHelpers.h"
using namespace swift;
// Check that swift::once calls the function, with the correct argument
TEST(OnceTest, once_calls_function) {
static swift::once_t predicate;
bool wasCalled = false;
swift::once(predicate, [](void *ctx) {
bool *pWasCalled = static_cast<bool *>(ctx);
*pWasCalled = true;
}, &wasCalled);
ASSERT_TRUE(wasCalled);
}
// Check that calling swift::once twice only calls the function once
TEST(OnceTest, once_calls_only_once) {
static swift::once_t predicate;
unsigned callCount = 0;
void (*fn)(void *) = [](void *ctx) {
unsigned *pCallCount = static_cast<unsigned *>(ctx);
++*pCallCount;
};
swift::once(predicate, fn, &callCount);
swift::once(predicate, fn, &callCount);
ASSERT_EQ(1u, callCount);
}
// Check that swift::once works when threaded
TEST(OnceTest, once_threaded) {
void (*fn)(void *) = [](void *ctx) {
unsigned *pCallCount = static_cast<unsigned *>(ctx);
++*pCallCount;
};
for (unsigned tries = 0; tries < 1000; ++tries) {
swift::once_t predicate = {0};
unsigned callCount = 0;
threadedExecute(16, [&](int) {
swift::once(predicate, fn, &callCount);
});
ASSERT_EQ(1u, callCount);
}
}