limited_async_pool_test.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package util
  2. import (
  3. "fmt"
  4. "github.com/stretchr/testify/assert"
  5. "sort"
  6. "testing"
  7. "time"
  8. )
  9. func TestAsyncPool(t *testing.T) {
  10. p := NewLimitedAsyncExecutor(3)
  11. p.Execute(FirstFunc)
  12. p.Execute(SecondFunc)
  13. p.Execute(ThirdFunc)
  14. p.Execute(FourthFunc)
  15. p.Execute(FifthFunc)
  16. var sorted_results []int
  17. for i := 0; i < 5; i++ {
  18. f := p.NextFuture()
  19. x := f.Await().(int)
  20. println(x)
  21. sorted_results = append(sorted_results, x)
  22. }
  23. assert.True(t, sort.IntsAreSorted(sorted_results), "results should be sorted")
  24. }
  25. func FirstFunc() any {
  26. fmt.Println("-- Executing first function --")
  27. time.Sleep(70 * time.Millisecond)
  28. fmt.Println("-- First Function finished --")
  29. return 1
  30. }
  31. func SecondFunc() any {
  32. fmt.Println("-- Executing second function --")
  33. time.Sleep(50 * time.Millisecond)
  34. fmt.Println("-- Second Function finished --")
  35. return 2
  36. }
  37. func ThirdFunc() any {
  38. fmt.Println("-- Executing third function --")
  39. time.Sleep(20 * time.Millisecond)
  40. fmt.Println("-- Third Function finished --")
  41. return 3
  42. }
  43. func FourthFunc() any {
  44. fmt.Println("-- Executing fourth function --")
  45. time.Sleep(100 * time.Millisecond)
  46. fmt.Println("-- Fourth Function finished --")
  47. return 4
  48. }
  49. func FifthFunc() any {
  50. fmt.Println("-- Executing fifth function --")
  51. time.Sleep(40 * time.Millisecond)
  52. fmt.Println("-- Fourth fifth finished --")
  53. return 5
  54. }