- Notifications
You must be signed in to change notification settings - Fork 10.5k
/
Copy pathexecute_child_on_await.swift
109 lines (90 loc) · 2.52 KB
/
execute_child_on_await.swift
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
// RUN: %target-run-simple-swift(-parse-as-library -target %target-swift-5.1-abi-triple -Xfrontend -concurrency-model=task-to-thread -g -Xlinker -object_path_lto -Xlinker /tmp/abc.o)
// REQUIRES: concurrency
// REQUIRES: executable_test
// REQUIRES: freestanding
// REQUIRES: concurrency_runtime
@_spi(_TaskToThreadModel)import _Concurrency
import StdlibUnittest
import Darwin
vara=0;
func foo()async->Int{
a +=1
print("a is now \(a)")
return a
}
func bar()async->Int{
a +=2
print("a is now \(a)")
return a
}
func asyncFib(_ n:Int, _ expected_thread:pthread_t)async->Int{
expectEqual(pthread_self(), expected_thread);
if n ==0 || n ==1{
return n
}
asyncletfirst=asyncFib(n-2, expected_thread)
asyncletsecond=asyncFib(n-1, expected_thread)
return(await second)+(await first)
}
func fib(_ n:Int)->Int{
varfirst=0
varsecond=1
for_in0..<n {
lettemp= first
first = second
second = temp + first
}
return first
}
@mainstructMain{
staticfunc main(){
lettests=TestSuite("Execute child task on await")
tests.test("Basic async let only execute on await"){
Task.runInline{
asyncleta=foo()
asyncletb=bar()
expectEqual(await b,2)
expectEqual(await a,3)
// Re-querying a completed task should return original result and not
// reexecute it
expectEqual(await b,2)
}
}
tests.test("Nested async lets that only execute on await"){
Task.runInline{
letresult=awaitasyncFib(10,pthread_self())
expectEqual(result,fib(10))
}
}
tests.test("Task group execute child task on await simple"){
a =0
Task.runInline{
awaitwithTaskGroup(of:Int.self, body :{ group in
letcurrentThread=pthread_self()
group.addTask{
expectEqual(pthread_self(), currentThread);
returnawaitfoo()
}
group.addTask{
expectEqual(pthread_self(), currentThread);
returnawaitbar()
}
})
}
}
tests.test("Task groups with nested structured concurrency"){
Task.runInline{
awaitwithTaskGroup(of:Int.self, body :{ group in
letcurrentThread=pthread_self()
group.addTask{
returnawaitasyncFib(10, currentThread);
}
group.addTask{
returnawaitasyncFib(5, currentThread);
}
})
}
}
runAllTests()
}
}