github.com/anacrolix/torrent@v1.61.0/dial-pool.go (about)

     1  package torrent
     2  
     3  import (
     4  	"context"
     5  )
     6  
     7  type dialPool struct {
     8  	resCh chan DialResult
     9  	addr  string
    10  	left  int
    11  }
    12  
    13  func (me *dialPool) getFirst() (res DialResult) {
    14  	for me.left > 0 && res.Conn == nil {
    15  		res = <-me.resCh
    16  		me.left--
    17  	}
    18  	return
    19  }
    20  
    21  func (me *dialPool) add(ctx context.Context, dialer Dialer) {
    22  	me.left++
    23  	go func() {
    24  		me.resCh <- DialResult{
    25  			dialFromSocket(ctx, dialer, me.addr),
    26  			dialer,
    27  		}
    28  	}()
    29  }
    30  
    31  func (me *dialPool) startDrainer() {
    32  	go me.drainAndCloseRemainingDials()
    33  }
    34  
    35  func (me *dialPool) drainAndCloseRemainingDials() {
    36  	for me.left > 0 {
    37  		conn := (<-me.resCh).Conn
    38  		me.left--
    39  		if conn != nil {
    40  			conn.Close()
    41  		}
    42  	}
    43  }