Skip to content

Commit

Permalink
limit the number of goroutines (#97)
Browse files Browse the repository at this point in the history
  • Loading branch information
achille-roussel authored and f2prateek committed Apr 26, 2016
1 parent af9e7d5 commit 2d840d8
Showing 1 changed file with 17 additions and 0 deletions.
17 changes: 17 additions & 0 deletions analytics.go
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,12 @@ type Client struct {
now func() time.Time
once sync.Once
wg sync.WaitGroup

// These synchronization primitives are used to control how many goroutines
// are spawned by the client for uploads.
upmtx sync.Mutex
upcond sync.Cond
upcount int
}

// New client with write key.
Expand All @@ -146,6 +152,7 @@ func New(key string) *Client {
uid: uid,
}

c.upcond.L = &c.upmtx
return c
}

Expand Down Expand Up @@ -243,12 +250,22 @@ func (c *Client) Close() error {
}

func (c *Client) sendAsync(msgs []interface{}) {
c.upmtx.Lock()
for c.upcount == 1000 {
c.upcond.Wait()
}
c.upcount++
c.upmtx.Unlock()
c.wg.Add(1)
go func() {
err := c.send(msgs)
if err != nil {
c.logf(err.Error())
}
c.upmtx.Lock()
c.upcount--
c.upcond.Signal()
c.upmtx.Unlock()
c.wg.Done()
}()
}
Expand Down

0 comments on commit 2d840d8

Please sign in to comment.