// Copyright 2021 Liuxiangchao iwind.liu@gmail.com. All rights reserved. //go:build script // +build script package js type ContextPool struct { ch chan *Context maxSize int } func NewContextPool(maxSize int) *ContextPool { if maxSize <= 0 { maxSize = 128 } return &ContextPool{ ch: make(chan *Context, maxSize), maxSize: maxSize, } } func (this *ContextPool) MaxSize() int { return this.maxSize } func (this *ContextPool) Size() int { return len(this.ch) } func (this *ContextPool) Get() *Context { // 不需要default语句,我们要确保整个Pool中只有固定的元素,防止内存溢出 select { case ctx := <-this.ch: return ctx } } func (this *ContextPool) Put(ctx *Context) { ctx.Cleanup() select { case this.ch <- ctx: default: ctx.Close() } } func (this *ContextPool) IsUsing() bool { return len(this.ch) != this.maxSize } func (this *ContextPool) Close() { Loop: for { select { case ctx := <-this.ch: ctx.Close() default: break Loop } } }