Skip to content

Commit

Permalink
Fix: Added locks around counter (#4)
Browse files Browse the repository at this point in the history
  • Loading branch information
vishal-bihani authored Oct 5, 2024
1 parent b76d42d commit 64ebfa0
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 0 deletions.
55 changes: 55 additions & 0 deletions benchmark_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
package tsid

import (
"fmt"
"sync"
"testing"
)

func BenchmarkGenerate(b *testing.B) {

b.Run("one goroutine", func(b *testing.B) {

tsidFactory, err := TsidFactoryBuilder().
WithNode(1).
Build()

if err != nil {
b.FailNow()
}

for i := 0; i < b.N; i++ {
tsidFactory.Generate()
}
})

b.Run("multiple goroutines", func(b *testing.B) {

goroutineCount := 10
wg := &sync.WaitGroup{}

for i := 0; i < goroutineCount; i++ {

wg.Add(1)
go func(iterationCount int, wg *sync.WaitGroup) {
defer wg.Done()
tsidFactory, err := TsidFactoryBuilder().
WithNode(1).
Build()

if err != nil {
fmt.Errorf("Failed to instantiate tsid factory with error: %s", err)
return
}

for i := 0; i < b.N; i++ {
tsidFactory.Generate()
}

}(b.N, wg)
}

wg.Wait()
})

}
4 changes: 4 additions & 0 deletions tsid_factory.go
Original file line number Diff line number Diff line change
Expand Up @@ -109,17 +109,21 @@ func (factory *tsidFactory) Generate() (*tsid, error) {
func (factory *tsidFactory) getTime() (int64, error) {
time := factory.clock.UnixMilli()
if time <= factory.lastTime {
lock.Lock()
factory.counter++
carry := uint32(factory.counter) >> factory.counterBits
factory.counter = factory.counter & factory.counterMask
time = factory.lastTime + int64(carry)
lock.Unlock()

} else {
value, err := factory.getRandomValue()
if err != nil {
return 0, err
}
lock.Lock()
factory.counter = value
lock.Unlock()
}
factory.lastTime = time
return (time - factory.customEpoch), nil
Expand Down

0 comments on commit 64ebfa0

Please sign in to comment.