github.com/rolandhe/saber@v0.0.4/example/queue/main.go (about)

     1  package main
     2  
     3  import (
     4  	"fmt"
     5  	"github.com/rolandhe/saber/gocc"
     6  	"log"
     7  	"time"
     8  )
     9  
    10  func main() {
    11  	productAndConsumerUsingChanQueue()
    12  	//consumerWaitChanQ()
    13  }
    14  
    15  func consumerWaitChanQ() {
    16  	q := gocc.NewDefaultBlockingQueue[int64](10)
    17  	waiter := gocc.NewCountdownLatch(1)
    18  	go func() {
    19  		for {
    20  			elem, ok := q.PullTimeout(time.Second * 20)
    21  			if ok {
    22  				v := elem.GetValue()
    23  				end := time.Now().UnixNano()
    24  				log.Printf("cost %d\n", end-v)
    25  				waiter.Down()
    26  				break
    27  			}
    28  		}
    29  	}()
    30  
    31  	time.Sleep(time.Millisecond * 800)
    32  
    33  	ok := q.TryOffer(time.Now().UnixNano())
    34  	log.Printf("offer:%v\n", ok)
    35  
    36  	waiter.Wait()
    37  }
    38  
    39  func productAndConsumerUsingChanQueue() {
    40  	q := gocc.NewDefaultBlockingQueue[int](10)
    41  	productAndConsumerUsingQueue(q)
    42  }
    43  
    44  func productAndConsumerUsingQueue(q gocc.BlockingQueue[int]) {
    45  	waiter := gocc.NewCountdownLatch(1000)
    46  	for i := 1; i <= 10; i++ {
    47  		go func(id int) {
    48  			for {
    49  				elem, ok := q.PullTimeout(time.Millisecond * 100)
    50  				if !ok {
    51  					log.Printf("wait timeout g:%d\n", id)
    52  					continue
    53  				}
    54  				v := elem.GetValue()
    55  				time.Sleep(time.Millisecond * 100)
    56  				log.Printf("end g:%d,using %d nano\n", id, v)
    57  				if 0 == waiter.Down() {
    58  					break
    59  				}
    60  			}
    61  		}(i)
    62  	}
    63  
    64  	start := time.Now().UnixNano()
    65  	for i := 1; i <= 1000; {
    66  		if q.OfferTimeout(i, time.Millisecond*1000) {
    67  			i++
    68  			log.Printf("offer timeout g:%d\n", i)
    69  			continue
    70  		}
    71  	}
    72  
    73  	waiter.Wait()
    74  	cost := time.Now().UnixNano() - start
    75  	fmt.Printf("end, cost %d nano\n", cost)
    76  }