github.com/Schaudge/grailbase@v0.0.0-20240223061707-44c758a471c0/syncqueue/syncqueue_test.go (about) 1 // Copyright 2018 GRAIL, Inc. All rights reserved. 2 // Use of this source code is governed by the Apache-2.0 3 // license that can be found in the LICENSE file. 4 5 package syncqueue_test 6 7 import ( 8 "fmt" 9 "testing" 10 11 "github.com/Schaudge/grailbase/syncqueue" 12 "github.com/stretchr/testify/require" 13 ) 14 15 func ExampleLIFO() { 16 q := syncqueue.NewLIFO() 17 q.Put("item0") 18 q.Put("item1") 19 q.Close() 20 v0, ok := q.Get() 21 fmt.Println("Item 0:", v0.(string), ok) 22 v1, ok := q.Get() 23 fmt.Println("Item 1:", v1.(string), ok) 24 v2, ok := q.Get() 25 fmt.Println("Item 2:", v2, ok) 26 // Output: 27 // Item 0: item1 true 28 // Item 1: item0 true 29 // Item 2: <nil> false 30 } 31 32 func TestLIFOWithThreads(t *testing.T) { 33 q := syncqueue.NewLIFO() 34 ch := make(chan string, 3) 35 36 // Check if "ch" has any data. 37 chanEmpty := func() bool { 38 select { 39 case <-ch: 40 return false 41 default: 42 return true 43 } 44 } 45 46 go func() { 47 for { 48 val, ok := q.Get() 49 if !ok { 50 break 51 } 52 ch <- val.(string) 53 } 54 }() 55 s := []string{} 56 q.Put("item0") 57 q.Put("item1") 58 s = append(s, <-ch, <-ch) 59 require.True(t, chanEmpty()) 60 61 q.Put("item2") 62 s = append(s, <-ch) 63 require.True(t, chanEmpty()) 64 65 require.Equal(t, []string{"item1", "item0", "item2"}, s) 66 }