github.com/spi-ca/misc@v1.0.1/q/string_queue.go (about)

     1  package q
     2  
     3  import (
     4  	"container/list"
     5  )
     6  
     7  // NewStringQueue creates a non blocking string queue channel.
     8  func NewStringQueue() (chan<- string, <-chan string) {
     9  	send := make(chan string, 1)
    10  	receive := make(chan string, 1)
    11  	go manageStringQueue(send, receive)
    12  	return send, receive
    13  }
    14  
    15  func manageStringQueue(send <-chan string, receive chan<- string) {
    16  	queue := list.New()
    17  	defer close(receive)
    18  	for {
    19  		if front := queue.Front(); front == nil {
    20  			if value, ok := <-send; ok {
    21  				queue.PushBack(value)
    22  			} else {
    23  				break
    24  			}
    25  		} else {
    26  			select {
    27  			case receive <- front.Value.(string):
    28  				queue.Remove(front)
    29  			case value, ok := <-send:
    30  				if ok {
    31  					queue.PushBack(value)
    32  				}
    33  			}
    34  		}
    35  	}
    36  }