Skip to content

Commit 2d840d8

Browse files
achille-rousself2prateek
authored andcommitted
limit the number of goroutines (#97)
1 parent af9e7d5 commit 2d840d8

File tree

1 file changed

+17
-0
lines changed

1 file changed

+17
-0
lines changed

analytics.go

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -127,6 +127,12 @@ type Client struct {
127127
now func() time.Time
128128
once sync.Once
129129
wg sync.WaitGroup
130+
131+
// These synchronization primitives are used to control how many goroutines
132+
// are spawned by the client for uploads.
133+
upmtx sync.Mutex
134+
upcond sync.Cond
135+
upcount int
130136
}
131137

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

155+
c.upcond.L = &c.upmtx
149156
return c
150157
}
151158

@@ -243,12 +250,22 @@ func (c *Client) Close() error {
243250
}
244251

245252
func (c *Client) sendAsync(msgs []interface{}) {
253+
c.upmtx.Lock()
254+
for c.upcount == 1000 {
255+
c.upcond.Wait()
256+
}
257+
c.upcount++
258+
c.upmtx.Unlock()
246259
c.wg.Add(1)
247260
go func() {
248261
err := c.send(msgs)
249262
if err != nil {
250263
c.logf(err.Error())
251264
}
265+
c.upmtx.Lock()
266+
c.upcount--
267+
c.upcond.Signal()
268+
c.upmtx.Unlock()
252269
c.wg.Done()
253270
}()
254271
}

0 commit comments

Comments
 (0)