github.com/qiuhoude/go-web@v0.0.0-20220223060959-ab545e78f20d/prepare/14_concurrent/pool/main.go (about) 1 package main 2 3 //https://github.com/smallnest/go-concurrent-quiz 4 import ( 5 "bytes" 6 "fmt" 7 "runtime" 8 "sync" 9 "time" 10 ) 11 12 var pool = sync.Pool{New: func() interface{} { return new(bytes.Buffer) }} 13 14 /* 15 A: 不能编译 16 B: 可以编译,运行时正常,内存稳定 17 C: 可以编译,运行时内存可能暴涨 答案 18 D: 可以编译,运行时内存先暴涨,但是过一会会回收掉 19 */ 20 func main() { 21 go func() { 22 for { 23 processRequest(1 << 28) // 256MiB 24 } 25 }() 26 for i := 0; i < 1000; i++ { 27 go func() { 28 for { 29 processRequest(1 << 10) // 1KiB 30 } 31 }() 32 } 33 var stats runtime.MemStats 34 for i := 0; ; i++ { 35 runtime.ReadMemStats(&stats) 36 fmt.Printf("Cycle %d: %dB\n", i, stats.Alloc) 37 time.Sleep(time.Second) 38 runtime.GC() 39 } 40 } 41 func processRequest(size int) { 42 b := pool.Get().(*bytes.Buffer) 43 time.Sleep(500 * time.Millisecond) 44 b.Grow(size) 45 pool.Put(b) 46 time.Sleep(1 * time.Millisecond) 47 }