Debian Codegraph @

stress/v2/stress_client/util.go

raw symbols SCIP
1 package stressClient
2
3 import (
4 "crypto/rand"
5 "fmt"
6 "log"
7 "strconv"
8 "sync"
9 )
10
11 // ###########################################
12 // ConcurrencyLimiter and associated methods #
13 // ###########################################
14
15 // ConcurrencyLimiter ensures that no more than a specified
16 // max number of goroutines are running.
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 // NewConcurrencyLimiter returns a configured limiter that will
27 // ensure that calls to Increment will block if the max is hit.
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 // Increment will increase the count of running goroutines by 1.
39 // if the number is currently at the max, the call to Increment
40 // will block until another goroutine decrements.
41 func (c *ConcurrencyLimiter) Increment() {
42 r := make(chan struct{})
43 c.inc <- r
44 <-r
45 }
46
47 // Decrement will reduce the count of running goroutines by 1
48 func (c *ConcurrencyLimiter) Decrement() {
49 c.dec <- struct{}{}
50 }
51
52 // NewMax resets the max of a ConcurrencyLimiter.
53 func (c *ConcurrencyLimiter) NewMax(i int) {
54 c.Lock()
55 defer c.Unlock()
56 c.max = i
57 }
58
59 // handleLimits runs in a goroutine to manage the count of
60 // running goroutines.
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 // Utility interger parsing function
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 // Utility for making random strings of length n
85 func randStr(n int) string {
86 b := make([]byte, n/2)
87 _, _ = rand.Read(b)
88 return fmt.Sprintf("%x", b)
89 }