Fix rpc go routine leak
This commit is contained in:
56
util/socket/pool.go
Normal file
56
util/socket/pool.go
Normal file
@@ -0,0 +1,56 @@
|
||||
package socket
|
||||
|
||||
import (
|
||||
"sync"
|
||||
)
|
||||
|
||||
type Pool struct {
|
||||
sync.RWMutex
|
||||
pool map[string]*Socket
|
||||
}
|
||||
|
||||
func (p *Pool) Get(id string) (*Socket, bool) {
|
||||
// attempt to get existing socket
|
||||
p.RLock()
|
||||
socket, ok := p.pool[id]
|
||||
if ok {
|
||||
p.RUnlock()
|
||||
return socket, ok
|
||||
}
|
||||
p.RUnlock()
|
||||
|
||||
// create new socket
|
||||
socket = New(id)
|
||||
// save socket
|
||||
p.Lock()
|
||||
p.pool[id] = socket
|
||||
p.Unlock()
|
||||
// return socket
|
||||
return socket, false
|
||||
}
|
||||
|
||||
func (p *Pool) Release(s *Socket) {
|
||||
p.Lock()
|
||||
defer p.Unlock()
|
||||
|
||||
// close the socket
|
||||
s.Close()
|
||||
delete(p.pool, s.id)
|
||||
}
|
||||
|
||||
// Close the pool and delete all the sockets
|
||||
func (p *Pool) Close() {
|
||||
p.Lock()
|
||||
defer p.Unlock()
|
||||
for id, sock := range p.pool {
|
||||
sock.Close()
|
||||
delete(p.pool, id)
|
||||
}
|
||||
}
|
||||
|
||||
// NewPool returns a new socket pool
|
||||
func NewPool() *Pool {
|
||||
return &Pool{
|
||||
pool: make(map[string]*Socket),
|
||||
}
|
||||
}
|
@@ -9,6 +9,7 @@ import (
|
||||
|
||||
// Socket is our pseudo socket for transport.Socket
|
||||
type Socket struct {
|
||||
id string
|
||||
// closed
|
||||
closed chan bool
|
||||
// remote addr
|
||||
@@ -119,8 +120,9 @@ func (s *Socket) Close() error {
|
||||
// New returns a new pseudo socket which can be used in the place of a transport socket.
|
||||
// Messages are sent to the socket via Accept and receives from the socket via Process.
|
||||
// SetLocal/SetRemote should be called before using the socket.
|
||||
func New() *Socket {
|
||||
func New(id string) *Socket {
|
||||
return &Socket{
|
||||
id: id,
|
||||
closed: make(chan bool),
|
||||
local: "local",
|
||||
remote: "remote",
|
||||
|
Reference in New Issue
Block a user