github.com/sunvim/utils@v0.1.0/workpool/workpool_test.go (about) 1 package workpool 2 3 import ( 4 "fmt" 5 "testing" 6 "time" 7 8 "github.com/sunvim/utils/errors" 9 ) 10 11 // template 12 func TestWorkerPoolStart(t *testing.T) { 13 wp := New(10) // Set the maximum number of threads 14 wp.SetTimeout(time.Millisecond) 15 for i := 0; i < 20; i++ { // Open 20 requests 16 ii := i 17 wp.Do(func() error { 18 for j := 0; j < 10; j++ { 19 fmt.Println(fmt.Sprintf("%v->\t%v", ii, j)) 20 time.Sleep(1 * time.Millisecond) 21 } 22 // time.Sleep(1 * time.Second) 23 return nil 24 }) 25 } 26 27 err := wp.Wait() 28 if err != nil { 29 fmt.Println(err) 30 } 31 fmt.Println("down") 32 } 33 34 // Support for error return 35 func TestWorkerPoolError(t *testing.T) { 36 wp := New(10) // Set the maximum number of threads 37 for i := 0; i < 20; i++ { 38 ii := i 39 wp.Do(func() error { 40 for j := 0; j < 10; j++ { 41 fmt.Println(fmt.Sprintf("%v->\t%v", ii, j)) 42 if ii == 1 { 43 return errors.Cause(errors.New("my test err")) 44 } 45 time.Sleep(1 * time.Millisecond) 46 } 47 48 return nil 49 // time.Sleep(1 * time.Second) 50 // return errors.New("my test err") 51 }) 52 } 53 54 err := wp.Wait() 55 if err != nil { 56 fmt.Println(err) 57 } 58 fmt.Println("down") 59 } 60 61 // Determine whether completion (non-blocking) is placed in the workpool and wait for execution results 62 func TestWorkerPoolDoWait(t *testing.T) { 63 wp := New(5) // Set the maximum number of threads 64 for i := 0; i < 10; i++ { 65 ii := i 66 wp.DoWait(func() error { 67 for j := 0; j < 5; j++ { 68 fmt.Println(fmt.Sprintf("%v->\t%v", ii, j)) 69 // if ii == 1 { 70 // return errors.New("my test err") 71 // } 72 time.Sleep(1 * time.Millisecond) 73 } 74 75 return nil 76 // time.Sleep(1 * time.Second) 77 // return errors.New("my test err") 78 }) 79 } 80 81 err := wp.Wait() 82 if err != nil { 83 fmt.Println(err) 84 } 85 fmt.Println("down") 86 } 87 88 // Determine whether it is complete (non-blocking) 89 func TestWorkerPoolIsDone(t *testing.T) { 90 wp := New(5) // Set the maximum number of threads 91 for i := 0; i < 10; i++ { 92 // ii := i 93 wp.Do(func() error { 94 for j := 0; j < 5; j++ { 95 // fmt.Println(fmt.Sprintf("%v->\t%v", ii, j)) 96 time.Sleep(1 * time.Millisecond) 97 } 98 return nil 99 }) 100 101 fmt.Println(wp.IsDone()) 102 } 103 wp.Wait() 104 fmt.Println(wp.IsDone()) 105 fmt.Println("down") 106 }