Files
waf-platform/EdgeNode/internal/js/context_pool.go
2026-02-04 20:27:13 +08:00

62 lines
1020 B
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// 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
}
}
}