-
Notifications
You must be signed in to change notification settings - Fork 10.4k
/
Copy pathOnce.cpp
88 lines (68 loc) · 2.27 KB
/
Once.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
//===--- 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 <cstring>
#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;
unsigned callCount = 0;
// We're being naughty here; swift::once_t is supposed to be global/static,
// but since we know what we're doing, this should be OK.
std::memset(&predicate, 0, sizeof(predicate));
threadedExecute(16, [&](int) { swift::once(predicate, fn, &callCount); });
ASSERT_EQ(1u, callCount);
}
}
// Check that swift::once works with a C++ lambda
TEST(OnceTest, once_lambda) {
static swift::once_t predicate;
unsigned callCount = 0;
auto fn = [&callCount]() {
++callCount;
};
swift::once(predicate, fn);
swift::once(predicate, fn);
ASSERT_EQ(1u, callCount);
}