Skip to content

Commit

Permalink
feat: lock
Browse files Browse the repository at this point in the history
  • Loading branch information
hiroyky committed Nov 20, 2023
1 parent ae929eb commit ba5005a
Showing 1 changed file with 12 additions and 1 deletion.
13 changes: 12 additions & 1 deletion memcache/pool.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package memcache
import (
"bufio"
"net"
"sync"
"time"
)

Expand All @@ -18,6 +19,7 @@ func newPool(addr net.Addr, c *Client) *pool {
}

type pool struct {
lk sync.Mutex
addr net.Addr
freeconns chan *conn
freeconnsNum int
Expand All @@ -43,23 +45,28 @@ func (p *pool) enqueueNewFreeConn() error {
}

go func() {
p.lk.Lock()
p.freeconnsNum++
p.openconnsNum++
p.lk.Unlock()
p.freeconns <- newConn
}()

return nil
}

func (p *pool) getConn() (*conn, error) {
if p.freeconnsNum == 0 && p.isNewConnOk() {
if p.freeconnsNum <= 0 && p.isNewConnOk() {
if err := p.enqueueNewFreeConn(); err != nil {
return nil, err
}
}

cn := <-p.freeconns
p.lk.Lock()
p.freeconnsNum--
p.lk.Unlock()

now := p.nowFunc()

if cn.isExpired(now) {
Expand All @@ -81,7 +88,9 @@ func (p *pool) isNewConnOk() bool {
func (p *pool) putFreeConn(cn *conn) {
if p.freeconnsNum < p.c.maxIdleConns() {
go func() {
p.lk.Lock()
p.freeconnsNum++
p.lk.Unlock()
p.freeconns <- cn
}()
} else {
Expand All @@ -91,5 +100,7 @@ func (p *pool) putFreeConn(cn *conn) {

func (p *pool) closeConn(cn *conn) {
_ = cn.nc.Close()
p.lk.Lock()
p.openconnsNum--
p.lk.Unlock()
}

0 comments on commit ba5005a

Please sign in to comment.