BewareMyPower commented on PR #1437:
URL:
https://github.com/apache/pulsar-client-go/pull/1437#issuecomment-3544845076
I wrote an example locally:
```golang
package main
import (
"fmt"
"math/rand"
"sync"
"time"
)
func main() {
slice := make([]int, 10)
for i := 0; i < len(slice); i++ {
slice[i] = rand.Intn(100)
}
wg := sync.WaitGroup{}
wg.Add(2)
lock := sync.Mutex{}
go func() {
start := time.Now()
sum := int64(0)
const n = 10000000
for i := 0; i < n; i++ {
partition := rand.Int()
lock.Lock()
sum = sum + int64(slice[partition%len(slice)])
lock.Unlock()
}
finished := time.Since(start)
fmt.Println(sum, " elapsed time:", finished, " avg: ",
finished.Nanoseconds()/n, " ns")
wg.Done()
}()
go func() {
for i := 0; i < 100; i++ {
lock.Lock()
for j := 0; j < 10; j++ {
slice = append(slice, rand.Intn(100))
}
lock.Unlock()
time.Sleep(1 * time.Millisecond)
}
wg.Done()
}()
wg.Wait()
}
```
- goroutine 1: choose a random element from the slice and calculate the sum
- goroutine 2: append 10 random values to the slice
Example outputs:
```
502615270 elapsed time: 166.572958ms avg: 16 ns
```
The lock contention is not as scary as thought by many people. I'm wondering
how much can be improved by using such an atomic approach?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]