diff options
Diffstat (limited to 'tests/benchmarks/thundering-herd-cond-var/stm.go')
-rw-r--r-- | tests/benchmarks/thundering-herd-cond-var/stm.go | 64 |
1 files changed, 64 insertions, 0 deletions
diff --git a/tests/benchmarks/thundering-herd-cond-var/stm.go b/tests/benchmarks/thundering-herd-cond-var/stm.go new file mode 100644 index 0000000..5ebf85b --- /dev/null +++ b/tests/benchmarks/thundering-herd-cond-var/stm.go @@ -0,0 +1,64 @@ +package stm + +import ( + "flag" + "sync" +) + + + +var nFlag = flag.Int( + "n", + 1_000, + "The number of iterations to execute", +) + +func MainTest() { + flag.Parse() + n := *nFlag + + const maxTokens = 25 + + for i := 0; i < n; i++ { + var mu sync.Mutex + consumer := sync.NewCond(&mu) + generator := sync.NewCond(&mu) + done := false + tokens := 0 + var pending sync.WaitGroup + for i := 0; i < 1000; i++ { + pending.Add(1) + go func() { + mu.Lock() + for { + if tokens > 0 { + tokens-- + generator.Signal() + break + } + consumer.Wait() + } + mu.Unlock() + pending.Done() + }() + } + go func() { + mu.Lock() + for !done { + if tokens < maxTokens { + tokens++ + consumer.Signal() + } else { + generator.Wait() + } + } + mu.Unlock() + }() + pending.Wait() + mu.Lock() + done = true + generator.Signal() + mu.Unlock() + } + +} |