-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathConcurrency_in_Go_test.go
2283 lines (2001 loc) · 47.4 KB
/
Concurrency_in_Go_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
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package sandbox
/*
Testing concurrency patterns and practices while reading
"Concurrency in Go. Tools and Techniques for Developers" by Katherine Cox-Buday
*/
import (
"context"
"fmt"
"log"
"math"
"math/rand"
"net/http"
"os"
"runtime"
"sort"
"strconv"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/stretchr/testify/assert"
"golang.org/x/time/rate"
)
// Limit the number of goroutines that can run at the same time
func Test_CountingSemaphore(t *testing.T) {
maxGoroutines := 5
semaphore := make(chan struct{}, maxGoroutines)
start := time.Now()
var cnt atomic.Int32
var wg sync.WaitGroup
for i := 0; i < 20; i++ {
wg.Add(1)
go func(i int) {
defer wg.Done()
semaphore <- struct{}{}
defer func() { <-semaphore }()
// Simulate a task
fmt.Printf("Running task %d\n", i)
time.Sleep(1 * time.Second)
cnt.Add(1)
}(i)
}
wg.Wait()
assert.Equal(t, int32(20), cnt.Load())
assert.Equal(t, 4, int(time.Since(start).Seconds())) // 20/5 = 4
}
/*
When you close a channel in Go, you're signaling that no more values will be sent on that channel.
However, any values that have already been sent on the channel before it was closed are still
available to be received. This is true for both buffered and unbuffered channels.
*/
func Test_Send_Close_Read(t *testing.T) {
stream := make(chan any)
go func() {
stream <- "value"
close(stream)
}()
for {
val, ok := <-stream
if !ok {
break
}
fmt.Println(val)
}
}
// CONCURRENCY PRIMITIVES
// sync package
func Test_SimulateWaitGroups(t *testing.T) {
var wg, cnt atomic.Int32
for i := range 10 {
wg.Add(1)
go func() {
defer wg.Add(-1)
log.Println("Task", i)
cnt.Add(1)
}()
}
for wg.Load() > 0 {
time.Sleep(100 * time.Millisecond)
}
assert.Equal(t, int32(0), wg.Load())
assert.Equal(t, int32(10), cnt.Load())
log.Println("Done")
}
func Test_WaitGroups(t *testing.T) {
var wg sync.WaitGroup
var cnt atomic.Int32
numTasks := 10
wg.Add(numTasks)
for i := range numTasks {
go func() {
defer wg.Done()
log.Println("Task", i)
cnt.Add(1)
}()
}
wg.Wait()
assert.Equal(t, int32(10), cnt.Load())
log.Println("Done")
}
// I don't really understand this one
func Test_Cond(t *testing.T) {
condition := false
conditionTrue := func() bool {
return condition
}
c := sync.NewCond(&sync.Mutex{})
go func() {
time.Sleep(1 * time.Second)
condition = true
c.Signal()
}()
c.L.Lock()
for conditionTrue() == false {
c.Wait()
}
c.L.Unlock()
assert.True(t, condition)
}
func Test_CondQueue(t *testing.T) {
c := sync.NewCond(&sync.Mutex{})
queue := make([]any, 0, 10)
removeFromQueue := func(delay time.Duration) {
time.Sleep(delay)
c.L.Lock()
queue = queue[1:]
fmt.Println("Removed from queue")
c.L.Unlock()
c.Signal()
}
for i := 0; i < 10; i++ {
c.L.Lock()
for len(queue) == 2 {
c.Wait()
}
fmt.Println("Adding to queue", i)
queue = append(queue, struct{}{})
go removeFromQueue(1 * time.Second)
c.L.Unlock()
}
}
// sync.Once - .Do() will be executed not more than once
func Test_Once(t *testing.T) {
cnt := 0
inc := func() {
cnt++
}
var once sync.Once
var wg sync.WaitGroup
wg.Add(100)
for i := 0; i < 100; i++ {
go func() {
once.Do(inc)
wg.Done()
}()
}
wg.Wait()
assert.Equal(t, 1, cnt)
}
// once counts how many times Do() was called
func Test_OnceDo(t *testing.T) {
once := sync.Once{}
//
var count int
increment := func() { count++ }
decrement := func() { count-- }
once.Do(increment)
once.Do(decrement)
// once counts how many times Do() was called, not how many times the function was executed
assert.Equal(t, 1, count)
}
// sync.Pool
// reusing the instances from the pool instead of instantiating the new ones
func Test_Pool(t *testing.T) {
myPool := &sync.Pool{
New: func() any {
log.Printf("Creating new instance")
return struct{}{}
},
}
myPool.Get() // Creating new instance
instance := myPool.Get() // Creating new instance
myPool.Put(instance) // Releasing instance
myPool.Get() // Reusing instance, no new instance created
}
//
// Channels
//
func Test_CloseChan(t *testing.T) {
dataStream := make(chan string)
go func() {
dataStream <- "hello from func"
}()
message, ok := <-dataStream
assert.True(t, ok) // value received
assert.Equal(t, "hello from func", message)
go func() {
log.Println("Closing channel")
close(dataStream)
}() // just to illustrate next lines
log.Println("Blocking on read from open channel")
message, ok = <-dataStream
log.Println("Channel closed, block released")
assert.False(t, ok) // channel closed
assert.Equal(t, "", message) // no message received
// reading from closed channel
// this way multiple downstreams can sit on blocking reading call
// until a single upstream doesn't close the channel
log.Println("Reading from Closed channel")
message, ok = <-dataStream
log.Println("Closed channel read is not blocking")
assert.False(t, ok) // channel closed, ok == false
assert.Equal(t, "", message) // no message received
if ok { // closing of closed channel will panic
close(dataStream)
}
// check before close:
if _, ok := <-dataStream; ok {
close(dataStream)
}
}
func Test_RangingOverChannel(t *testing.T) {
intStream := make(chan int)
go func() {
defer close(intStream)
for i := range 10 {
intStream <- i
}
}()
sum := 0
for received := range intStream {
log.Println("Received", received)
sum += received
}
assert.Equal(t, 45, sum)
}
// unlocking multiple goroutines
func Test_UnlockingMultiple(t *testing.T) {
lockStream := make(chan any)
var wg sync.WaitGroup
for i := range 5 {
wg.Add(1)
go func(i int) {
defer wg.Done()
<-lockStream
log.Println("Worker", i, "unblocked")
}(i)
}
close(lockStream)
wg.Wait()
}
// Buffered Channel
func Test_BufferedChannel(t *testing.T) {
intStream := make(chan int, 4)
go func(n int) {
defer close(intStream)
defer log.Println("Producer Done.")
for i := range n {
log.Println("Sending", i)
intStream <- i
}
}(10)
for i := range intStream {
log.Println("Receiving", i, "|", len(intStream), "in queue")
}
}
// Channel ownership
// owner responsible for writing to channel and closing channel
// returns read-only channel
// this ensures that:
// - writes won't happen on closed or nil channel
// - close will happen once
func Test_Channel_Owner(t *testing.T) {
channelOwner := func() <-chan int {
intStream := make(chan int, 5)
go func() {
defer close(intStream)
for i := range 10 {
intStream <- i
}
}()
return intStream
}
received := 0
ints := channelOwner()
for i := range ints {
log.Println("Received", i)
received++
}
assert.Equal(t, 10, received) // everything's received
}
// Select statement
func Test_Select(t *testing.T) {
start := time.Now()
block := make(chan any)
go func() {
time.Sleep(1 * time.Second)
close(block)
}()
select { // equal to simple blocking read `<-block`
case <-block:
log.Println("Unblocked in", time.Since(start))
}
log.Println("Done.")
//
// Both channels are ready at the same time
c1 := make(chan any)
close(c1)
c2 := make(chan any)
close(c2)
var c1Count, c2Count int
for i := 1000; i >= 0; i-- {
select {
case <-c1:
c1Count++
case <-c2:
c2Count++
}
}
fmt.Printf("c1Count: %d\nc2Count: %d\n", c1Count, c2Count)
// roughly equal chance of being selected, difference is less than 10%
assert.Less(t, math.Abs(float64(c2Count-c1Count)), float64(100))
//
// Timeout
timedOut := false
var c <-chan int
select {
case <-c:
case <-time.After(1 * time.Second):
timedOut = true
fmt.Println("Timed out.")
}
assert.True(t, timedOut)
//
// Default clause
defaulted := false
var c11 <-chan int
var c12 <-chan int
select {
case <-c11:
case <-c12:
default:
defaulted = true
log.Println("Defaulted")
}
assert.True(t, defaulted)
//
// Loop with default
// run default clause while waiting for the channel to unblock
done := make(chan any)
go func() {
time.Sleep(1 * time.Second)
close(done)
}()
workCounter := 0
keepGoing := true
for keepGoing {
select {
case <-done:
keepGoing = false
default:
}
workCounter++
time.Sleep(1 * time.Millisecond)
}
log.Println("Made", workCounter, "cycles before stopped")
assert.Less(t, 1, workCounter) // workCounter > 1
//
// Block forever
// select {}
}
// CONCURRENCY PATTERNS
func Test_Confinement(t *testing.T) {
chanOwner := func() <-chan int {
results := make(chan int, 5)
go func() {
defer close(results)
for i := 0; i <= 5; i++ {
results <- i
}
}()
return results
}
consumer := func(results <-chan int) {
for result := range results {
fmt.Printf("Received: %d\n", result)
}
fmt.Println("Done receiving!")
}
results := chanOwner()
consumer(results)
}
// Sending iteration variables out on a channel
func Test_For_Select_Loop(t *testing.T) {
done := make(chan any)
stringStream := make(chan string)
go func() {
time.Sleep(1 * time.Second)
done <- "timeout"
}()
go func() {
for {
s := <-stringStream
log.Printf("Received %s", s)
time.Sleep(520 * time.Millisecond)
}
}()
for _, s := range []string{"a", "b", "c"} {
select {
case <-done: // will read in 1 second no matter what? like a timeout?
return
case stringStream <- s: // blocking write, waiting to stringStream to be empty
}
}
}
// Looping infinitely waiting to be stopped
func Test_Loop_Infinitely(t *testing.T) {
done := make(chan any)
go func() {
time.Sleep(1 * time.Second)
close(done)
}()
i := 0
for {
select {
case <-done:
log.Println("Done")
assert.Equal(t, 5, i) // 5 times 200ms in 1 second
return
default:
// i++
// log.Println("Working")
// time.Sleep(200 * time.Millisecond)
}
// or here:
i++
log.Println("Working")
time.Sleep(200 * time.Millisecond)
}
}
// Goroutine leak demo
func Test_NoTermination(t *testing.T) {
worked := false
doWork := func(strings <-chan string) <-chan any {
completed := make(chan any)
go func() { // this goroutine will leak, never stop
defer fmt.Println("doWork exited.")
defer close(completed)
for s := range strings { // because this read will be blocked forever
fmt.Println(s)
worked = true
}
}()
return completed
}
doWork(nil)
assert.False(t, worked)
}
// termination example from the book
func Test_Termination_Example(t *testing.T) {
doWork := func(
done <-chan any, strings <-chan string,
) <-chan any {
terminated := make(chan any)
go func() {
defer fmt.Println("doWork exited.")
defer close(terminated)
for {
select {
case s := <-strings:
// Do something interesting
fmt.Println(s)
case <-done:
return
}
}
}()
return terminated
}
done := make(chan any)
terminated := doWork(done, nil)
go func() {
// Cancel the operation after 1 second.
time.Sleep(1 * time.Second)
fmt.Println("Canceling doWork goroutine...")
close(done)
}()
<-terminated
fmt.Println("Done.")
}
// termination example with something really being sent on strings chan
func Test_ProperTermination(t *testing.T) {
doWork := func(done <-chan any, strings <-chan string) <-chan any {
terminated := make(chan any)
go func() {
defer fmt.Println("doWork exited.")
defer close(terminated)
for {
select {
case s := <-strings:
// Do something interesting
fmt.Println("Working on", s)
case <-done:
return
}
}
}()
return terminated
}
done := make(chan any)
strings := make(chan string)
terminated := doWork(done, strings)
go func() {
// Cancel the operation after 1 second.
time.Sleep(1 * time.Second)
fmt.Println("Canceling doWork goroutine...")
close(done)
}()
for i := range 10 {
select {
case strings <- strconv.Itoa(i):
time.Sleep(150 * time.Millisecond)
case <-terminated:
// Join doWork goroutine with the main goroutine
fmt.Println("Done.")
return
// case <-done:
}
}
}
// Book Example
// Goroutine leak caused by Block on write to the channel
func Test_BlockOnWrite(t *testing.T) {
routineReturned := false
newRandStream := func() <-chan int {
randStream := make(chan int)
go func() {
defer fmt.Println("newRandStream closure exited.")
defer close(randStream)
for {
randStream <- rand.Int()
}
routineReturned = true // unreachable code, goroutine will wait forever
// should be handled like this:
// for {
// select {
// case randStream <- rand.Int():
// case <-done:
// return
// }
// }
}()
return randStream
}
randStream := newRandStream()
fmt.Println("3 random ints:")
for i := 1; i <= 3; i++ {
fmt.Printf("%d: %d\n", i, <-randStream)
}
assert.False(t, routineReturned)
}
// Fixing previous example
func Test_FixedBlockOnWrite(t *testing.T) {
routineReturned := false
newRandStream := func(done <-chan any) <-chan int {
randStream := make(chan int)
go func() {
defer fmt.Println("newRandStream closure exited.")
defer close(randStream)
for {
select {
case randStream <- rand.Int():
case <-done:
routineReturned = true
return
}
}
}()
return randStream
}
done := make(chan any)
defer close(done)
randStream := newRandStream(done)
fmt.Println("3 random ints:")
for i := 1; i <= 3; i++ {
fmt.Printf("%d: %d\n", i, <-randStream)
}
go func() {
<-done
assert.True(t, routineReturned)
}()
}
// Example:
// The or-channel. Pretty messed up code, just copy-pasted and tested
func Test_OrChannel(t *testing.T) {
var or func(channels ...<-chan any) <-chan any
or = func(channels ...<-chan any) <-chan any {
switch len(channels) {
case 0:
return nil
case 1:
return channels[0]
}
orDone := make(chan any)
go func() {
defer close(orDone)
switch len(channels) {
case 2:
select {
case <-channels[0]:
case <-channels[1]:
}
default:
select {
case <-channels[0]:
case <-channels[1]:
case <-channels[2]:
case <-or(append(channels[3:], orDone)...):
}
}
}()
return orDone
}
sig := func(after time.Duration) <-chan any {
c := make(chan any)
go func() {
defer close(c)
time.Sleep(after)
}()
return c
}
start := time.Now()
<-or(
sig(2*time.Hour),
sig(5*time.Minute),
sig(1*time.Second),
sig(1*time.Hour),
sig(1*time.Minute),
)
fmt.Printf("done after %v\n", time.Since(start))
assert.True(t, true)
}
// Example:
// return errors along the result from goroutine:
func Test_ReturnErrors(t *testing.T) {
type Result struct {
Url string
Error error
Response *http.Response
}
checkStatus := func(done <-chan interface{}, urls ...string) <-chan Result {
results := make(chan Result)
go func() {
defer close(results)
for _, url := range urls {
var result Result
resp, err := http.Get(url)
result = Result{Error: err, Url: url, Response: resp}
select {
case <-done:
return
case results <- result:
}
}
}()
return results
}
log.Println("Checking urls...")
done := make(chan interface{})
urls := []string{"https://www.google.com", "https://badhost"}
for result := range checkStatus(done, urls...) {
if result.Error != nil {
fmt.Printf("url: %s, error: %v\n", result.Url, result.Error)
continue
}
fmt.Printf("url: %s, Response: %v\n", result.Url, result.Response.Status)
}
close(done)
// stop if there are 3+ errors:
log.Println("Checking urls until there are 3 or more errors:")
done = make(chan interface{})
errCount := 0
urls = []string{"a", "https://www.google.com", "b", "c", "d"}
for result := range checkStatus(done, urls...) {
if result.Error != nil {
fmt.Printf("error: %v\n", result.Error)
errCount++
if errCount >= 3 {
fmt.Println("Too many errors, breaking!")
break
}
continue
}
fmt.Printf("Response: %v\n", result.Response.Status)
}
close(done)
}
// PIPELINES
//
// Generators
//
func strGenerator(done <-chan any, strSlice []string) <-chan string {
strChan := make(chan string)
go func() {
defer close(strChan)
for _, s := range strSlice {
select {
case <-done:
return
default:
strChan <- s
}
}
}()
return strChan
}
func Test_strGenerator(t *testing.T) {
strSlice := []string{"a", "b", "c"}
done := make(chan any)
defer close(done)
for s := range strGenerator(done, strSlice) {
log.Println(s)
}
}
// I think I'm gonna start collecting these pipeline functions
// in pipeline package (pipeline/main.go)
func Generator[T any](done <-chan any, strSlice []T) <-chan T {
outChan := make(chan T)
go func() {
defer close(outChan)
for _, s := range strSlice {
select {
case <-done:
return
case outChan <- s:
}
}
}()
return outChan
}
func Test_genericGenerator(t *testing.T) {
strSlice := []string{"a", "b", "c"}
done := make(chan any)
defer close(done)
for s := range Generator(done, strSlice) {
log.Println(s)
}
intSlice := []int{1, 2, 3, 4, 5, 69, 420}
done = make(chan any)
defer close(done)
for s := range Generator(done, intSlice) {
log.Println(s)
}
}
func StageFn[T any](done <-chan any, input <-chan T, fn func(v T) T) <-chan T {
outChan := make(chan T)
go func() {
defer close(outChan)
for {
select {
case <-done:
return
case outChan <- fn(<-input):
}
}
}()
return outChan
}
// Repeat repeats the values until done is closed.
func Repeat[T any](done <-chan any, values ...T) <-chan T {
outChan := make(chan T)
go func() {
defer close(outChan)
for {
for _, value := range values {
select {
case <-done:
return
case outChan <- value:
}
}
}
}()
return outChan
}
// RepeatFn repeats the result of fn() until done is closed.
func RepeatFn[T any](done <-chan any, fn func() T) <-chan T {
outChan := make(chan T)
go func() {
defer close(outChan)
for {
select {
case <-done:
return
case outChan <- fn():
}
}
}()
return outChan
}
// generate random ints for 100 microseconds
func Test_genericFnGenerator(t *testing.T) {
done := make(chan any)
go func() {
// time.Sleep(100 * time.Microsecond)
// close(done)
// or like this:
<-time.After(100 * time.Microsecond)
close(done)
}()
for i := range RepeatFn(done, rand.Int) {
log.Println(i)
}
}
// Take takes the first num values from the input channel and returns them in a new channel.
func Take[T any](done <-chan any, input <-chan T, num int) <-chan T {
output := make(chan T)
go func() {
defer close(output)
for range num {
select {
case <-done:
return
case output <- <-input:
}
}
}()
return output
}
// generate exactly 10 random ints and print half
func Test_10IntsGenerator(t *testing.T) {
done := make(chan any)
num := 0
for i := range Take(done, StageFn(done, RepeatFn(done, rand.Int), func(v int) int { return v / 2 }), 10) {
log.Println(i)
num++
}
assert.Equal(t, 10, num)
close(done)
// Once again but stage-by-stage:
// done = make(chan any)
// defer close(done)
// <-taker<-halver<-generator - why this doesn't work???
// generator := RepeatFn(done, rand.Int)
// halver := StageFn(done, generator, func(v int) int { return v / 2 })
// taker := Take(done, halver, 10)
// for i := range <-taker {
// log.Println(i)
// }
}
func Test_GeneratortoStage(t *testing.T) {
input := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
results := []int{}
done := make(chan any)
for n := range Take(done, StageFn(done, Generator(done, input), func(v int) int {
return v * 2
}), 10) {
results = append(results, n)
}
assert.Equal(t, []int{2, 4, 6, 8, 10, 12, 14, 16, 18, 20}, results)
close(done)
// <-taker<-halver<-generator
done = make(chan any)