| 1 |
package stressClient |
| 2 |
|
| 3 |
import ( |
| 4 |
"crypto/rand" |
| 5 |
"fmt" |
| 6 |
"log" |
| 7 |
"strconv" |
| 8 |
"sync" |
| 9 |
) |
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
type ConcurrencyLimiter struct { |
| 18 |
inc chan chan struct{} |
| 19 |
dec chan struct{} |
| 20 |
max int |
| 21 |
count int |
| 22 |
|
| 23 |
sync.Mutex |
| 24 |
} |
| 25 |
|
| 26 |
|
| 27 |
|
| 28 |
func NewConcurrencyLimiter(max int) *ConcurrencyLimiter { |
| 29 |
c := &ConcurrencyLimiter{ |
| 30 |
inc: make(chan chan struct{}), |
| 31 |
dec: make(chan struct{}, max), |
| 32 |
max: max, |
| 33 |
} |
| 34 |
go c.handleLimits() |
| 35 |
return c |
| 36 |
} |
| 37 |
|
| 38 |
|
| 39 |
|
| 40 |
|
| 41 |
func (c *ConcurrencyLimiter) Increment() { |
| 42 |
r := make(chan struct{}) |
| 43 |
c.inc <- r |
| 44 |
<-r |
| 45 |
} |
| 46 |
|
| 47 |
|
| 48 |
func (c *ConcurrencyLimiter) Decrement() { |
| 49 |
c.dec <- struct{}{} |
| 50 |
} |
| 51 |
|
| 52 |
|
| 53 |
func (c *ConcurrencyLimiter) NewMax(i int) { |
| 54 |
c.Lock() |
| 55 |
defer c.Unlock() |
| 56 |
c.max = i |
| 57 |
} |
| 58 |
|
| 59 |
|
| 60 |
|
| 61 |
func (c *ConcurrencyLimiter) handleLimits() { |
| 62 |
for { |
| 63 |
r := <-c.inc |
| 64 |
c.Lock() |
| 65 |
if c.count >= c.max { |
| 66 |
<-c.dec |
| 67 |
c.count-- |
| 68 |
} |
| 69 |
c.Unlock() |
| 70 |
c.count++ |
| 71 |
r <- struct{}{} |
| 72 |
} |
| 73 |
} |
| 74 |
|
| 75 |
|
| 76 |
func parseInt(s string) int { |
| 77 |
i, err := strconv.ParseInt(s, 10, 64) |
| 78 |
if err != nil { |
| 79 |
log.Fatalf("Error parsing integer:\n String: %v\n Error: %v\n", s, err) |
| 80 |
} |
| 81 |
return int(i) |
| 82 |
} |
| 83 |
|
| 84 |
|
| 85 |
func randStr(n int) string { |
| 86 |
b := make([]byte, n/2) |
| 87 |
_, _ = rand.Read(b) |
| 88 |
return fmt.Sprintf("%x", b) |
| 89 |
} |