add synchelper;

develop synchelper/v0.1.0
Ge Song 2 years ago
parent ff69d51e50
commit e484aaa1f9

@ -0,0 +1,18 @@
package synchelper
import "bytes"
// NewBytesBufferPool 返回新的 BytesBufferPool
func NewBytesBufferPool(initialSize, maximumSize int) BytesBufferPool {
return NewPool(
func() any {
return bytes.NewBuffer(make([]byte, 0, initialSize))
},
func(v *bytes.Buffer) bool {
return v.Cap() <= maximumSize
},
)
}
// BytesBufferPool 是 [*bytes.Buffer] 的资源池
type BytesBufferPool = Pool[*bytes.Buffer]

@ -0,0 +1,3 @@
module git.blauwelle.com/go/crate/synchelper
go 1.20

@ -0,0 +1,25 @@
package synchelper
import (
"io"
"sync"
)
// NewSyncWriter 返回写互斥的 writer
func NewSyncWriter(writer io.Writer) io.Writer {
return &syncWriter{
writer: writer,
lock: sync.Mutex{},
}
}
type syncWriter struct {
writer io.Writer
lock sync.Mutex
}
func (w *syncWriter) Write(p []byte) (n int, err error) {
w.lock.Lock()
defer w.lock.Unlock()
return w.writer.Write(p)
}

@ -0,0 +1,34 @@
package synchelper
import (
"sync"
)
// NewPool 初始化 Pool,
// newFn 是资源的构造函数,
// putCond 返回 true 时表示资源可以被放回 Pool 中.
func NewPool[T any](newFn func() any, putCond func(v T) bool) Pool[T] {
return Pool[T]{
pool: &sync.Pool{New: newFn},
putCond: putCond,
}
}
// Pool 是通用的资源池
type Pool[T any] struct {
pool *sync.Pool
putCond func(v T) bool
}
// Get 获取资源
func (pool Pool[T]) Get() T {
return pool.pool.Get().(T)
}
// Put 放回资源
func (pool Pool[T]) Put(v T) {
if !pool.putCond(v) {
return
}
pool.pool.Put(v)
}
Loading…
Cancel
Save