github.com/sunvim/utils@v0.1.0/queue/queue_test.go (about)

     1  package queue
     2  
     3  import (
     4  	"fmt"
     5  	"runtime"
     6  	"testing"
     7  	"time"
     8  )
     9  
    10  func TestWait(t *testing.T) {
    11  	que := New()
    12  	for i := 0; i < 10; i++ { //开启20个请求
    13  		que.Push(i)
    14  	}
    15  
    16  	go func() {
    17  		for {
    18  			fmt.Println(que.Pop().(int))
    19  			time.Sleep(1 * time.Second)
    20  		}
    21  	}()
    22  
    23  	go func() {
    24  		for {
    25  			fmt.Println(que.Pop().(int))
    26  			time.Sleep(1 * time.Second)
    27  		}
    28  	}()
    29  
    30  	que.Wait()
    31  	fmt.Println("down")
    32  }
    33  
    34  func TestClose(t *testing.T) {
    35  	que := New()
    36  	for i := 0; i < 10; i++ { //开启20个请求
    37  		que.Push(i)
    38  	}
    39  
    40  	go func() {
    41  		for {
    42  			v := que.Pop()
    43  			if v != nil {
    44  				fmt.Println(v.(int))
    45  				time.Sleep(1 * time.Second)
    46  			}
    47  		}
    48  	}()
    49  
    50  	go func() {
    51  		for {
    52  			v := que.Pop()
    53  			if v != nil {
    54  				fmt.Println(v.(int))
    55  				time.Sleep(1 * time.Second)
    56  			}
    57  		}
    58  	}()
    59  
    60  	que.Close()
    61  	que.Wait()
    62  	fmt.Println("down")
    63  }
    64  
    65  func TestTry(t *testing.T) {
    66  	que := New()
    67  
    68  	go func() {
    69  		for {
    70  			v, ok := que.TryPop()
    71  			if !ok {
    72  				fmt.Println("no")
    73  				time.Sleep(time.Second / 2)
    74  				runtime.Gosched() //出让时间片
    75  			}
    76  
    77  			if v != nil {
    78  				fmt.Println(v.(int))
    79  			}
    80  		}
    81  	}()
    82  
    83  	go func() {
    84  		for {
    85  			v, ok := que.TryPop()
    86  			if !ok {
    87  				fmt.Println("no")
    88  				time.Sleep(time.Second / 2)
    89  				runtime.Gosched() //出让时间片
    90  			}
    91  
    92  			if v != nil {
    93  				fmt.Println(v.(int))
    94  			}
    95  		}
    96  	}()
    97  
    98  	for i := 0; i < 10; i++ { //开启20个请求
    99  		que.Push(i)
   100  		time.Sleep(1 * time.Second)
   101  	}
   102  
   103  	que.Wait()
   104  	fmt.Println("down")
   105  }
   106  
   107  func TestTimeout(t *testing.T) {
   108  	que := New()
   109  	go func() {
   110  		for i := 0; i < 10; i++ { //开启20个请求
   111  			time.Sleep(1 * time.Second)
   112  			que.Push(i)
   113  
   114  		}
   115  	}()
   116  
   117  	go func() {
   118  		for {
   119  			b, ok := que.TryPopTimeout(100 * time.Microsecond)
   120  			if ok {
   121  				fmt.Println(b.(int))
   122  			} else {
   123  				fmt.Println("time out")
   124  			}
   125  		}
   126  	}()
   127  
   128  	time.Sleep(200 * time.Second)
   129  	que.Wait()
   130  	fmt.Println("down")
   131  }