limitlistener

package module
v1.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 11, 2024 License: MIT Imports: 4 Imported by: 0

README

GoDoc

limitlistener

This library makes it easy to limit the number of live threads for a given listener. This can be useful in a number of cases to ensure not too many connections will be processed at the same time rather than letting go create new goroutines like there is no tomorrow.

Any call to Accept() when the limit has been reached will wait for any of the currently running connections to close before accepting any new connection.

Usage

l, err := net.Listen("tcp", ":12345")
if err != nil {
    // ...
}

// limit to 128 concurrent processes
l = limitlistener.New(l, 128)

for {
    c, err := l.Accept()
    if err != nil {
        return err
    }

    // safe to start a goroutine here, will be limited to 128 routines
    go handleClient(c)
}

handleClient(c net.Conn) {
    defer c.Close()

    // ...
}

This can be used for a http.Server or anything that takes a net.Listener and will apply the limit as standard as possible. Multiple threads calling Accept() are also supported.

If using this with http.Server be careful to set a ReadTimeout or you may end blocked just with idle connections.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func New

func New(l net.Listener, max uint64) net.Listener

New wraps the listener in a limitListener so that only a specific number of connection can be opened at the same time.

Types

type Limiter

type Limiter struct {
	// contains filtered or unexported fields
}

Limiter works kind of like the reverse of a WaitGroup. It uses a straightforward locking process that will cause a lock to be required for Done() but considering the locking is only happening on limited operations it shouldn't be slow

func NewLimiter

func NewLimiter(max uint64) *Limiter

NewLimiter returns a new limiter with the given maximum number of ongoing processes

func (*Limiter) Add

func (l *Limiter) Add()

Add adds 1 to the limiter, waiting for availability if needed

func (*Limiter) Done

func (l *Limiter) Done()

Done frees one entry from limiter

func (*Limiter) SetMax

func (l *Limiter) SetMax(newMax uint64)

SetMax sets the maximum number of processes

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL