1 Star 0 Fork 2

联犀/driver-go

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
handlerpool.go 1.69 KB
一键复制 编辑 原始数据 按行查看 历史
杨磊 提交于 2024-10-10 22:32 . feat: 更新mod
package handler
import (
"container/list"
"sync"
"unsafe"
"gitee.com/unitedrhino/driver-go/v3/wrapper/cgo"
)
type AsyncResult struct {
Res unsafe.Pointer
N int
}
type Caller struct {
QueryResult chan *AsyncResult
FetchResult chan *AsyncResult
}
func NewCaller() *Caller {
return &Caller{
QueryResult: make(chan *AsyncResult, 1),
FetchResult: make(chan *AsyncResult, 1),
}
}
func (c *Caller) QueryCall(res unsafe.Pointer, code int) {
c.QueryResult <- &AsyncResult{
Res: res,
N: code,
}
}
func (c *Caller) FetchCall(res unsafe.Pointer, numOfRows int) {
c.FetchResult <- &AsyncResult{
Res: res,
N: numOfRows,
}
}
type poolReq struct {
idleHandler *Handler
}
type HandlerPool struct {
mu sync.RWMutex
count int
handlers chan *Handler
reqList *list.List
}
type Handler struct {
Handler cgo.Handle
Caller *Caller
}
func NewHandlerPool(count int) *HandlerPool {
c := &HandlerPool{
count: count,
handlers: make(chan *Handler, count),
reqList: list.New(),
}
for i := 0; i < count; i++ {
caller := NewCaller()
c.handlers <- &Handler{
Handler: cgo.NewHandle(caller),
Caller: caller,
}
}
return c
}
func (c *HandlerPool) Get() *Handler {
for {
select {
case wrapConn := <-c.handlers:
return wrapConn
default:
c.mu.Lock()
req := make(chan poolReq, 1)
c.reqList.PushBack(req)
c.mu.Unlock()
ret := <-req
return ret.idleHandler
}
}
}
func (c *HandlerPool) Put(handler *Handler) {
c.mu.Lock()
e := c.reqList.Front()
if e != nil {
req := e.Value.(chan poolReq)
c.reqList.Remove(e)
req <- poolReq{
idleHandler: handler,
}
c.mu.Unlock()
return
} else {
c.handlers <- handler
c.mu.Unlock()
return
}
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/unitedrhino/driver-go.git
git@gitee.com:unitedrhino/driver-go.git
unitedrhino
driver-go
driver-go
v3.30.1

搜索帮助

0d507c66 1850385 C8b1a773 1850385