github.com/egonelbre/exp@v0.0.0-20240430123955-ed1d3aa93911/ring/example/main.go (about) 1 package main 2 3 import ( 4 "fmt" 5 "math/rand" 6 "runtime" 7 "sync/atomic" 8 "time" 9 10 "github.com/egonelbre/exp/ring" 11 ) 12 13 var ( 14 TotalWritten int64 15 TotalRead int64 16 ) 17 18 func writer(data *ring.Ring) { 19 for i := 0; i < 1<<20; i++ { 20 cell := data.Allocate() 21 cell.Size = rand.Int63() & 0xFF 22 atomic.AddInt64(&TotalWritten, cell.Size) 23 cell.Enqueue() 24 25 runtime.Gosched() 26 } 27 } 28 29 func reader(data *ring.Ring) { 30 for { 31 cell := data.Dequeue() 32 if cell == nil { 33 panic("invalid value") 34 } 35 36 atomic.AddInt64(&TotalRead, cell.Size) 37 cell.Release() 38 } 39 } 40 41 func monitor(data *ring.Ring) { 42 for { 43 written, read := atomic.LoadInt64(&TotalWritten), atomic.LoadInt64(&TotalRead) 44 fmt.Printf("%d/%d\n", written, read) 45 time.Sleep(time.Second) 46 } 47 } 48 49 func main() { 50 data := ring.New() 51 go monitor(data) 52 for i := 0; i < 64; i++ { 53 go reader(data) 54 } 55 go writer(data) 56 57 time.Sleep(10 * time.Second) 58 }