Skip to content

Commit

Permalink
style: change the way lock
Browse files Browse the repository at this point in the history
  • Loading branch information
justlorain committed Jul 1, 2023
1 parent 8f1400d commit 91a94a7
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 16 deletions.
14 changes: 7 additions & 7 deletions cool/conn.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ var _ net.Conn = (*Conn)(nil)

type Conn struct {
net.Conn
sync.RWMutex
mu sync.RWMutex
unusable bool
c *cool
t time.Time
Expand All @@ -34,8 +34,8 @@ type Conn struct {
// Close overrides the net.Conn Close method
// put the usable connection back to the pool instead of closing it
func (cc *Conn) Close() error {
cc.RLock()
defer cc.RUnlock()
cc.mu.RLock()
defer cc.mu.RUnlock()
if cc.unusable {
if cc.Conn != nil {
return cc.Conn.Close()
Expand All @@ -46,13 +46,13 @@ func (cc *Conn) Close() error {
}

func (cc *Conn) MarkUnusable() {
cc.Lock()
defer cc.Unlock()
cc.mu.Lock()
defer cc.mu.Unlock()
cc.unusable = true
}

func (cc *Conn) IsUnusable() bool {
cc.RLock()
defer cc.RUnlock()
cc.mu.RLock()
defer cc.mu.RUnlock()
return cc.unusable
}
18 changes: 9 additions & 9 deletions cool/cool.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,8 @@ type Cool interface {
type Producer func() (net.Conn, error)

type cool struct {
sync.Once
sync.RWMutex
once sync.Once
mu sync.RWMutex
options *options
connC chan net.Conn
producer Producer
Expand All @@ -69,10 +69,10 @@ func New(init, max int, producer Producer, opts ...Option) (Cool, error) {
}

func (c *cool) Get() (net.Conn, error) {
c.RLock()
c.mu.RLock()
connC := c.connC
producer := c.producer
c.RUnlock()
c.mu.RUnlock()
if connC == nil {
return nil, ErrClosed
}
Expand All @@ -91,7 +91,7 @@ func (c *cool) Get() (net.Conn, error) {
}

func (c *cool) Close() {
c.Do(func() {
c.once.Do(func() {
connC := c.connC
c.options = nil
c.connC = nil
Expand All @@ -104,17 +104,17 @@ func (c *cool) Close() {
}

func (c *cool) Len() int {
c.RLock()
defer c.RUnlock()
c.mu.RLock()
defer c.mu.RUnlock()
return len(c.connC)
}

func (c *cool) put(conn net.Conn) error {
if conn == nil {
return ErrNilConn
}
c.RLock()
defer c.RUnlock()
c.mu.RLock()
defer c.mu.RUnlock()
if c.connC == nil {
// cool is closed
return conn.Close()
Expand Down

0 comments on commit 91a94a7

Please sign in to comment.