Created
November 9, 2015 13:12
-
-
Save momchil-velikov/816c8f9c2a3430601474 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"sync" | |
"sync/atomic" | |
"time" | |
) | |
var pool *sync.Pool | |
type Packet struct { | |
buf []byte | |
cnt int32 | |
} | |
func frob(p *Packet, buf []byte) { | |
// FIXME: do stuff with our part | |
// do_stuff(buf) | |
// Decrement refcount; if we're the last, return to the pool. | |
if atomic.AddInt32(&p.cnt, -1) == 0 { | |
pool.Put(p) | |
} | |
} | |
func main() { | |
pool = new(sync.Pool) | |
pool.New = func() interface{} { return new(Packet) } | |
const N = 1000 | |
for i := 0; i < N; i++ { | |
// Get buffer | |
p := pool.Get().(*Packet) | |
// Ensure it has enough capacity. | |
if p.buf == nil || cap(p.buf) < 10 { | |
p.buf = make([]byte, 10) | |
} else { | |
p.buf = p.buf[:0] | |
} | |
// FIXME: fill buffer with data | |
p.buf = append(p.buf, 1, 2, 3, 4, 5, 6, 7, 8) | |
// Spawn workers. | |
const M = 5 | |
atomic.StoreInt32(&p.cnt, M) | |
for j := 0; j < M; j++ { | |
// Pass just a part of the buffer to each worker | |
go frob(p, p.buf[j:j+1]) | |
} | |
} | |
<-time.After(2 * time.Second) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment