github.com/wangyougui/gf/v2@v2.6.5/container/gqueue/gqueue_z_example_test.go (about) 1 // Copyright GoFrame Author(https://goframe.org). All Rights Reserved. 2 // 3 // This Source Code Form is subject to the terms of the MIT License. 4 // If a copy of the MIT was not distributed with this file, 5 // You can obtain one at https://github.com/wangyougui/gf. 6 7 package gqueue_test 8 9 import ( 10 "context" 11 "fmt" 12 "time" 13 14 "github.com/wangyougui/gf/v2/container/gqueue" 15 "github.com/wangyougui/gf/v2/os/gtimer" 16 ) 17 18 func ExampleNew() { 19 n := 10 20 q := gqueue.New() 21 22 // Producer 23 for i := 0; i < n; i++ { 24 q.Push(i) 25 } 26 27 // Close the queue in three seconds. 28 gtimer.SetTimeout(context.Background(), time.Second*3, func(ctx context.Context) { 29 q.Close() 30 }) 31 32 // The consumer constantly reads the queue data. 33 // If there is no data in the queue, it will block. 34 // The queue is read using the queue.C property exposed 35 // by the queue object and the selectIO multiplexing syntax 36 // example: 37 // for { 38 // select { 39 // case v := <-queue.C: 40 // if v != nil { 41 // fmt.Println(v) 42 // } else { 43 // return 44 // } 45 // } 46 // } 47 for { 48 if v := q.Pop(); v != nil { 49 fmt.Print(v) 50 } else { 51 break 52 } 53 } 54 55 // Output: 56 // 0123456789 57 } 58 59 func ExampleQueue_Push() { 60 q := gqueue.New() 61 62 for i := 0; i < 10; i++ { 63 q.Push(i) 64 } 65 66 fmt.Println(q.Pop()) 67 fmt.Println(q.Pop()) 68 fmt.Println(q.Pop()) 69 70 // Output: 71 // 0 72 // 1 73 // 2 74 } 75 76 func ExampleQueue_Pop() { 77 q := gqueue.New() 78 79 for i := 0; i < 10; i++ { 80 q.Push(i) 81 } 82 83 fmt.Println(q.Pop()) 84 q.Close() 85 fmt.Println(q.Pop()) 86 87 // Output: 88 // 0 89 // <nil> 90 } 91 92 func ExampleQueue_Close() { 93 q := gqueue.New() 94 95 for i := 0; i < 10; i++ { 96 q.Push(i) 97 } 98 99 time.Sleep(time.Millisecond) 100 q.Close() 101 102 fmt.Println(q.Len()) 103 fmt.Println(q.Pop()) 104 105 // May Output: 106 // 0 107 // <nil> 108 } 109 110 func ExampleQueue_Len() { 111 q := gqueue.New() 112 113 q.Push(1) 114 q.Push(2) 115 116 fmt.Println(q.Len()) 117 118 // May Output: 119 // 2 120 } 121 122 func ExampleQueue_Size() { 123 q := gqueue.New() 124 125 q.Push(1) 126 q.Push(2) 127 128 // Size is alias of Len. 129 fmt.Println(q.Size()) 130 131 // May Output: 132 // 2 133 }