-
Notifications
You must be signed in to change notification settings - Fork 0
/
example_test.go
701 lines (542 loc) · 14.4 KB
/
example_test.go
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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
package async_test
import (
"fmt"
"sync"
"time"
"github.com/b97tsk/async"
)
// This example demonstrates how to spawn Tasks with different paths.
// The lower path, the higher priority.
// This example creates a Task with path "aa" for additional computations
// and another Task with path "zz" for printing results.
// The former runs before the latter because "aa" < "zz".
func Example() {
// Create an Executor.
var myExecutor async.Executor
// Set up an autorun function to run an Executor automatically whenever a Coroutine is spawned or resumed.
// The best practice is to pass a function that does not block. See Example (NonBlocking).
myExecutor.Autorun(myExecutor.Run)
// Create two States.
s1, s2 := async.NewState(1), async.NewState(2)
// Although States can be created without the help of Executors,
// they might only be safe for use by one and only one Executor because of data races.
// Without proper synchronization, it's better only to spawn Coroutines to read or update States.
var sum, product async.State[int]
myExecutor.Spawn("aa", func(co *async.Coroutine) async.Result { // The path of co is "aa".
co.Watch(s1, s2) // Let co depend on s1 and s2, so co can re-run whenever s1 or s2 changes.
sum.Set(s1.Get() + s2.Get())
product.Set(s1.Get() * s2.Get())
return co.Await() // Awaits signals or state changes.
})
// The above Task re-runs whenever s1 or s2 changes. As an example, this is fine.
// In practice, one should probably use Memos to avoid unnecessary recomputations. See Example (Memo).
op := async.NewState('+')
myExecutor.Spawn("zz", func(co *async.Coroutine) async.Result { // The path of co is "zz".
co.Watch(op)
fmt.Println("op =", "'"+string(op.Get())+"'")
switch op.Get() {
case '+':
// The path of an inner Coroutine is relative to its outer one.
co.Spawn("sum", func(co *async.Coroutine) async.Result { // The path of inner co is "zz/sum".
fmt.Println("s1 + s2 =", sum.Get())
return co.Await(&sum)
})
case '*':
co.Spawn("product", func(co *async.Coroutine) async.Result { // The path of inner co is "zz/product".
fmt.Println("s1 * s2 =", product.Get())
return co.Await(&product)
})
}
return co.Await()
})
fmt.Println("--- SEPARATOR ---")
// The followings create several Tasks to mutate States.
// They share the same path, "/", which is lower than "aa" and "zz".
// Remember that, the lower path, the higher priority.
// Updating States should have higher priority, so that when there are multiple update Tasks,
// they can run together before any read Task.
// This reduces the number of reads that have to react on update.
myExecutor.Spawn("/", async.Do(func() {
s1.Set(3)
s2.Set(4)
}))
fmt.Println("--- SEPARATOR ---")
myExecutor.Spawn("/", async.Do(func() {
op.Set('*')
}))
fmt.Println("--- SEPARATOR ---")
myExecutor.Spawn("/", async.Do(func() {
s1.Set(5)
s2.Set(6)
}))
fmt.Println("--- SEPARATOR ---")
myExecutor.Spawn("/", async.Do(func() {
s1.Set(7)
s2.Set(8)
op.Set('+')
}))
// Output:
// op = '+'
// s1 + s2 = 3
// --- SEPARATOR ---
// s1 + s2 = 7
// --- SEPARATOR ---
// op = '*'
// s1 * s2 = 12
// --- SEPARATOR ---
// s1 * s2 = 30
// --- SEPARATOR ---
// op = '+'
// s1 + s2 = 15
}
// This example demonstrates how to use Memos to memoize cheap computations.
// Memos are evaluated lazily. They take effect only when they are acquired.
func Example_memo() {
var myExecutor async.Executor
myExecutor.Autorun(myExecutor.Run)
s1, s2 := async.NewState(1), async.NewState(2)
sum := async.NewMemo(&myExecutor, "aa", func(co *async.Coroutine, s *async.State[int]) {
co.Watch(s1, s2)
if v := s1.Get() + s2.Get(); v != s.Get() {
s.Set(v) // Update s only when its value changes to stop unnecessary propagation.
}
})
product := async.NewMemo(&myExecutor, "aa", func(co *async.Coroutine, s *async.State[int]) {
co.Watch(s1, s2)
if v := s1.Get() * s2.Get(); v != s.Get() {
s.Set(v)
}
})
op := async.NewState('+')
myExecutor.Spawn("zz", func(co *async.Coroutine) async.Result {
co.Watch(op)
fmt.Println("op =", "'"+string(op.Get())+"'")
switch op.Get() {
case '+':
co.Spawn("sum", func(co *async.Coroutine) async.Result {
fmt.Println("s1 + s2 =", sum.Get())
return co.Await(sum)
})
case '*':
co.Spawn("product", func(co *async.Coroutine) async.Result {
fmt.Println("s1 * s2 =", product.Get())
return co.Await(product)
})
}
return co.Await()
})
fmt.Println("--- SEPARATOR ---")
myExecutor.Spawn("/", async.Do(func() {
s1.Set(3)
s2.Set(4)
}))
fmt.Println("--- SEPARATOR ---")
myExecutor.Spawn("/", async.Do(func() {
op.Set('*')
}))
fmt.Println("--- SEPARATOR ---")
myExecutor.Spawn("/", async.Do(func() {
s1.Set(5)
s2.Set(6)
}))
fmt.Println("--- SEPARATOR ---")
myExecutor.Spawn("/", async.Do(func() {
s1.Set(7)
s2.Set(8)
op.Set('+')
}))
// Output:
// op = '+'
// s1 + s2 = 3
// --- SEPARATOR ---
// s1 + s2 = 7
// --- SEPARATOR ---
// op = '*'
// s1 * s2 = 12
// --- SEPARATOR ---
// s1 * s2 = 30
// --- SEPARATOR ---
// op = '+'
// s1 + s2 = 15
}
// This example demonstrates how to set up an autorun function to run
// an Executor in a goroutine automatically whenever a Coroutine is spawned or
// resumed.
func Example_nonBlocking() {
var wg sync.WaitGroup // For keeping track of goroutines.
var myExecutor async.Executor
myExecutor.Autorun(func() {
wg.Add(1)
go func() {
defer wg.Done()
myExecutor.Run()
}()
})
s1, s2 := async.NewState(1), async.NewState(2)
sum := async.NewMemo(&myExecutor, "aa", func(co *async.Coroutine, s *async.State[int]) {
co.Watch(s1, s2)
if v := s1.Get() + s2.Get(); v != s.Get() {
s.Set(v)
}
})
product := async.NewMemo(&myExecutor, "aa", func(co *async.Coroutine, s *async.State[int]) {
co.Watch(s1, s2)
if v := s1.Get() * s2.Get(); v != s.Get() {
s.Set(v)
}
})
op := async.NewState('+')
myExecutor.Spawn("zz", func(co *async.Coroutine) async.Result {
co.Watch(op)
fmt.Println("op =", "'"+string(op.Get())+"'")
switch op.Get() {
case '+':
co.Spawn("sum", func(co *async.Coroutine) async.Result {
fmt.Println("s1 + s2 =", sum.Get())
return co.Await(sum)
})
case '*':
co.Spawn("product", func(co *async.Coroutine) async.Result {
fmt.Println("s1 * s2 =", product.Get())
return co.Await(product)
})
}
return co.Await()
})
wg.Wait() // Wait for autorun to complete.
fmt.Println("--- SEPARATOR ---")
myExecutor.Spawn("/", async.Do(func() {
s1.Set(3)
s2.Set(4)
}))
wg.Wait()
fmt.Println("--- SEPARATOR ---")
myExecutor.Spawn("/", async.Do(func() {
op.Set('*')
}))
wg.Wait()
fmt.Println("--- SEPARATOR ---")
myExecutor.Spawn("/", async.Do(func() {
s1.Set(5)
s2.Set(6)
}))
wg.Wait()
fmt.Println("--- SEPARATOR ---")
myExecutor.Spawn("/", async.Do(func() {
s1.Set(7)
s2.Set(8)
op.Set('+')
}))
wg.Wait()
// Output:
// op = '+'
// s1 + s2 = 3
// --- SEPARATOR ---
// s1 + s2 = 7
// --- SEPARATOR ---
// op = '*'
// s1 * s2 = 12
// --- SEPARATOR ---
// s1 * s2 = 30
// --- SEPARATOR ---
// op = '+'
// s1 + s2 = 15
}
// This example demonstrates how a Task can conditionally depend on a State.
func Example_conditional() {
var myExecutor async.Executor
myExecutor.Autorun(myExecutor.Run)
s1, s2, s3 := async.NewState(1), async.NewState(2), async.NewState(7)
myExecutor.Spawn("aa", func(co *async.Coroutine) async.Result {
co.Watch(s1, s2) // Always depends on s1 and s2.
v := s1.Get() + s2.Get()
if v%2 == 0 {
co.Watch(s3) // Conditionally depends on s3.
v *= s3.Get()
}
fmt.Println(v)
return co.Await()
})
myExecutor.Spawn("/", async.Do(func() { s3.Notify() })) // Nothing happens.
myExecutor.Spawn("/", async.Do(func() { s1.Set(s1.Get() + 1) }))
myExecutor.Spawn("/", async.Do(func() { s3.Notify() }))
myExecutor.Spawn("/", async.Do(func() { s2.Set(s2.Get() + 1) }))
myExecutor.Spawn("/", async.Do(func() { s3.Notify() })) // Nothing happens.
// Output:
// 3
// 28
// 28
// 5
}
// This example demonstrates how a Memo can conditionally depend on a State.
func Example_conditionalMemo() {
var myExecutor async.Executor
myExecutor.Autorun(myExecutor.Run)
s1, s2, s3 := async.NewState(1), async.NewState(2), async.NewState(7)
m := async.NewMemo(&myExecutor, "aa", func(co *async.Coroutine, s *async.State[int]) {
co.Watch(s1, s2) // Always depends on s1 and s2.
v := s1.Get() + s2.Get()
if v%2 == 0 {
co.Watch(s3) // Conditionally depends on s3.
v *= s3.Get()
}
s.Set(v)
})
myExecutor.Spawn("zz", func(co *async.Coroutine) async.Result {
co.Watch(m)
fmt.Println(m.Get())
return co.Await()
})
myExecutor.Spawn("/", async.Do(func() { s3.Notify() })) // Nothing happens.
myExecutor.Spawn("/", async.Do(func() { s1.Set(s1.Get() + 1) }))
myExecutor.Spawn("/", async.Do(func() { s3.Notify() }))
myExecutor.Spawn("/", async.Do(func() { s2.Set(s2.Get() + 1) }))
myExecutor.Spawn("/", async.Do(func() { s3.Notify() })) // Nothing happens.
// Output:
// 3
// 28
// 28
// 5
}
// This example demonstrates how to end a Task.
// It creates a Task that prints the value of a State whenever it changes.
// The Task only prints 0, 1, 2 and 3 because it is ended after 3.
func Example_end() {
var myExecutor async.Executor
myExecutor.Autorun(myExecutor.Run)
var myState async.State[int]
myExecutor.Spawn("zz", func(co *async.Coroutine) async.Result {
co.Watch(&myState)
v := myState.Get()
fmt.Println(v)
if v < 3 {
return co.Await()
}
return co.End()
})
for i := 1; i <= 5; i++ {
myExecutor.Spawn("/", async.Do(func() { myState.Set(i) }))
}
fmt.Println(myState.Get()) // Prints 5.
// Output:
// 0
// 1
// 2
// 3
// 5
}
// This example demonstrates how to add a function call before a Task re-runs,
// or after a Task ends.
func Example_defer() {
var myExecutor async.Executor
myExecutor.Autorun(myExecutor.Run)
var myState async.State[int]
myExecutor.Spawn("zz", func(co *async.Coroutine) async.Result {
co.Watch(&myState)
v := myState.Get()
co.Defer(func() { fmt.Println(v, myState.Get()) })
if v < 3 {
return co.Await()
}
return co.End()
})
for i := 1; i <= 5; i++ {
myExecutor.Spawn("/", async.Do(func() { myState.Set(i) }))
}
fmt.Println(myState.Get()) // Prints 5.
// Output:
// 0 1
// 1 2
// 2 3
// 3 3
// 5
}
// This example demonstrates how a Coroutine can switch from one Task to
// another.
func Example_switch() {
var myExecutor async.Executor
myExecutor.Autorun(myExecutor.Run)
var myState async.State[int]
myExecutor.Spawn("zz", func(co *async.Coroutine) async.Result {
co.Watch(&myState)
v := myState.Get()
fmt.Println(v)
if v < 3 {
return co.Await()
}
return co.Switch(func(co *async.Coroutine) async.Result {
co.Watch(&myState)
v := myState.Get()
fmt.Println(v, "(switched)")
if v < 5 {
return co.Await()
}
return co.End()
})
})
for i := 1; i <= 7; i++ {
myExecutor.Spawn("/", async.Do(func() { myState.Set(i) }))
}
fmt.Println(myState.Get()) // Prints 7.
// Output:
// 0
// 1
// 2
// 3
// 3 (switched)
// 4 (switched)
// 5 (switched)
// 7
}
// This example demonstrates how to chain multiple Tasks together to be worked
// on in sequence by a Coroutine.
func Example_chain() {
var myExecutor async.Executor
myExecutor.Autorun(myExecutor.Run)
var myState async.State[int]
myExecutor.Spawn("zz", async.Chain(
func(co *async.Coroutine) async.Result {
co.Watch(&myState)
v := myState.Get()
fmt.Println(v, "(first)")
if v < 3 {
return co.Await()
}
return co.Switch(func(co *async.Coroutine) async.Result {
co.Watch(&myState)
v := myState.Get()
fmt.Println(v, "(switched)")
if v < 5 {
return co.Await()
}
return co.End()
})
},
func(co *async.Coroutine) async.Result {
co.Watch(&myState)
v := myState.Get()
fmt.Println(v, "(second)")
if v < 7 {
return co.Await()
}
return co.End()
},
))
for i := 1; i <= 9; i++ {
myExecutor.Spawn("/", async.Do(func() { myState.Set(i) }))
}
fmt.Println(myState.Get()) // Prints 9.
// Output:
// 0 (first)
// 1 (first)
// 2 (first)
// 3 (first)
// 3 (switched)
// 4 (switched)
// 5 (switched)
// 5 (second)
// 6 (second)
// 7 (second)
// 9
}
// This example demonstrates how to yield a Coroutine only for it to resume
// later with another Task.
// It computes two values in separate goroutines sequentially, then prints
// their sum.
// It showcases what yielding can do, not that it's a useful pattern.
func Example_yield() {
var wg sync.WaitGroup // For keeping track of goroutines.
var myExecutor async.Executor
myExecutor.Autorun(func() {
wg.Add(1)
go func() {
defer wg.Done()
myExecutor.Run()
}()
})
var myState struct {
async.Signal
v1, v2 int
}
myExecutor.Spawn("/", func(co *async.Coroutine) async.Result {
wg.Add(1)
go func() {
defer wg.Done()
time.Sleep(500 * time.Millisecond) // Heavy work #1 here.
ans := 15
myExecutor.Spawn("/", async.Do(func() {
myState.v1 = ans
myState.Notify()
}))
}()
co.Watch(&myState)
// Yield preserves Events that are being watched.
return co.Yield(func(co *async.Coroutine) async.Result {
wg.Add(1)
go func() {
defer wg.Done()
time.Sleep(500 * time.Millisecond) // Heavy work #2 here.
ans := 27
myExecutor.Spawn("/", async.Do(func() {
myState.v2 = ans
myState.Notify()
}))
}()
co.Watch(&myState)
return co.Yield(async.Do(func() {
fmt.Println("v1 + v2 =", myState.v1+myState.v2)
}))
})
})
wg.Wait()
// Output:
// v1 + v2 = 42
}
func ExampleTask_Then() {
var myExecutor async.Executor
myExecutor.Autorun(myExecutor.Run)
var myState async.State[int]
a := func(co *async.Coroutine) async.Result {
co.Watch(&myState)
v := myState.Get()
fmt.Println(v, "(a)")
if v < 3 {
return co.Await()
}
return co.Switch(func(co *async.Coroutine) async.Result {
co.Watch(&myState)
v := myState.Get()
fmt.Println(v, "(switched)")
if v < 5 {
return co.Await()
}
return co.End()
})
}
b := func(co *async.Coroutine) async.Result {
co.Watch(&myState)
v := myState.Get()
fmt.Println(v, "(b)")
if v < 7 {
return co.Await()
}
return co.End()
}
myExecutor.Spawn("zz", async.Task(a).Then(b))
for i := 1; i <= 9; i++ {
myExecutor.Spawn("/", async.Do(func() { myState.Set(i) }))
}
fmt.Println(myState.Get()) // Prints 9.
// Output:
// 0 (a)
// 1 (a)
// 2 (a)
// 3 (a)
// 3 (switched)
// 4 (switched)
// 5 (switched)
// 5 (b)
// 6 (b)
// 7 (b)
// 9
}