gitee.com/sy_183/go-common@v1.0.5-0.20231205030221-958cfe129b47/container/sync-queue_test.go (about) 1 package container 2 3 import ( 4 "fmt" 5 "sync" 6 "testing" 7 ) 8 9 func TestSyncQueue(t *testing.T) { 10 q := NewSyncQueue[int](20) 11 for i := 0; i < 20; i++ { 12 fmt.Println(q.TryPush(i)) 13 } 14 for i := 0; i < 20; i++ { 15 fmt.Println(q.TryPop()) 16 } 17 } 18 19 func BenchmarkSyncQueue(b *testing.B) { 20 l := 1 << 16 21 g := 8 22 b.Run("sync-queue", func(b *testing.B) { 23 q := NewSyncQueue[int](l * g) 24 for i := 0; i < b.N; i++ { 25 wg := sync.WaitGroup{} 26 for i := 0; i < g; i++ { 27 wg.Add(1) 28 go func() { 29 for i := 0; i < l; i++ { 30 q.TryPush(i) 31 } 32 wg.Done() 33 }() 34 } 35 wg.Wait() 36 for i := 0; i < g; i++ { 37 wg.Add(1) 38 go func() { 39 for i := 0; i < l; i++ { 40 q.TryPop() 41 } 42 wg.Done() 43 }() 44 } 45 wg.Wait() 46 } 47 }) 48 b.Run("chan", func(b *testing.B) { 49 c := make(chan int, l*g) 50 for i := 0; i < b.N; i++ { 51 wg := sync.WaitGroup{} 52 for i := 0; i < g; i++ { 53 wg.Add(1) 54 go func() { 55 for i := 0; i < l; i++ { 56 select { 57 case c <- i: 58 default: 59 } 60 } 61 wg.Done() 62 }() 63 } 64 wg.Wait() 65 for i := 0; i < g; i++ { 66 wg.Add(1) 67 go func() { 68 for i := 0; i < l; i++ { 69 select { 70 case <-c: 71 default: 72 } 73 } 74 wg.Done() 75 }() 76 } 77 wg.Wait() 78 } 79 }) 80 }