Skip to content

Instantly share code, notes, and snippets.

@astavonintsc
Last active December 18, 2019 02:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save astavonintsc/78ade5bd75c6a072e82ed052986ed952 to your computer and use it in GitHub Desktop.
Save astavonintsc/78ade5bd75c6a072e82ed052986ed952 to your computer and use it in GitHub Desktop.
package main
import (
"container/list"
"fmt"
"time"
)
func main() {
cache := list.New()
ch := make(chan string, 3)
exitCh := make(chan interface{})
go func() {
for i := 0; i < 5; i++ {
time.Sleep(100 * time.Millisecond)
select {
case msg := <-ch:
fmt.Println("from channel:", msg)
default:
msg := cache.Front()
if msg != nil {
cache.Remove(msg)
fmt.Println("from cache:", msg.Value)
}
}
}
close(exitCh)
}()
for i := 0; i < 5; i++ {
msg := fmt.Sprintf("message %d", i)
select {
case ch <- msg:
fmt.Println("sent to channel:", msg)
default:
cache.PushBack(msg)
fmt.Println("sent to cache:", msg)
}
}
<-exitCh
}
// Output:
//
// sent to channel: message 0
// sent to channel: message 1
// sent to channel: message 2
// sent to cache: message 3
// sent to cache: message 4
// from channel: message 0
// from channel: message 1
// from channel: message 2
// from cache: message 3
// from cache: message 4
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment