Skip to content

Commit d0248af

Browse files
committed
[Test] Make implicit_weak_capture.swift more robust.
This test creates an object then checks a weak reference to that object on a background thread. It was doing this check after 10ms, and any small hiccup could potentially delay the object's destruction enough to spuriously fail. Rearrange the test to check the weak reference in a loop for several seconds before giving up. This makes it very fast on success (it's done the moment it sees nil) while being robust against up to several seconds of delay in destroying the object if that happens. rdar://149868181
1 parent 47e5ede commit d0248af

File tree

1 file changed

+33
-20
lines changed

1 file changed

+33
-20
lines changed

test/expr/closure/implicit_weak_capture.swift

Lines changed: 33 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -13,37 +13,50 @@ func runIn10ms(_ closure: @escaping @Sendable () -> Void) {
1313
}
1414
}
1515

16+
let checkInterval = 10_000_000
17+
let checkIters = 1000
18+
1619
final class Weak: Sendable {
1720
let property = "Self exists"
1821

19-
func test() {
20-
runIn10ms { [weak self] in
21-
if let self {
22-
// Use implicit self -- this should not result in a strong capture
23-
_ = property
24-
fatalError("Self was unexpectedly captured strongly")
25-
} else {
26-
print("Self was captured weakly (1)")
22+
func test() async -> (Task<Void, Never>, Task<Void, Never>) {
23+
let t1 = Task { [weak self] in
24+
for _ in 0..<checkIters {
25+
if let self {
26+
// Use implicit self -- this should not result in a strong capture
27+
_ = property
28+
} else {
29+
print("Self was captured weakly (1)")
30+
return
31+
}
32+
try! await Task.sleep(nanoseconds: 10_000_000)
2733
}
34+
fatalError("Self was unexpectedly captured strongly")
2835
}
2936

30-
runIn10ms { [weak self] in
31-
guard let self else {
32-
print("Self was captured weakly (2)")
33-
return
34-
}
37+
let t2 = Task { [weak self] in
38+
for _ in 0..<checkIters {
39+
guard let self else {
40+
print("Self was captured weakly (2)")
41+
return
42+
}
3543

36-
// Use implicit self -- this should not result in a strong capture
37-
_ = property
38-
39-
runIn10ms { [self] in
4044
// Use implicit self -- this should not result in a strong capture
4145
_ = property
42-
fatalError("Self was unexpectedly captured strongly")
46+
47+
runIn10ms { [self] in
48+
// Use implicit self -- this should not result in a strong capture
49+
_ = property
50+
}
51+
try! await Task.sleep(nanoseconds: 10_000_000)
4352
}
53+
fatalError("Self was unexpectedly captured strongly")
4454
}
55+
56+
return (t1, t2)
4557
}
4658
}
4759

48-
Weak().test()
49-
try await Task.sleep(nanoseconds: 30_000_000)
60+
let (t1, t2) = await Weak().test()
61+
await t1.value
62+
await t2.value

0 commit comments

Comments
 (0)