[HAR-73] add a singleton package and tests in utils

need to return unique validator id for new nodes added into a shard

add a unit test of singleton package
test unique id generation, and non-unique id

Signed-off-by: Leo Chen <leo@harmony.one>
pull/93/head
Leo Chen 6 years ago
parent 6e4f74778b
commit a989a84966
  1. 28
      utils/singleton.go
  2. 41
      utils/singleton_test.go

@ -0,0 +1,28 @@
/* This module keeps all struct used as singleton */
package utils
import (
"sync"
"sync/atomic"
)
type UniqueValidatorId struct {
uniqueId uint32
}
var instance *UniqueValidatorId
var once sync.Once
func GetUniqueValidatorIdInstance() *UniqueValidatorId {
once.Do(func() {
instance = &UniqueValidatorId{
uniqueId: 0,
}
})
return instance
}
func (s *UniqueValidatorId) GetUniqueId() uint32 {
return atomic.AddUint32(&s.uniqueId, 1)
}

@ -0,0 +1,41 @@
package utils
import (
"sync"
"testing"
"time"
)
var NumThreads int = 20
func TestSingleton(t *testing.T) {
si := GetUniqueValidatorIdInstance()
var wg sync.WaitGroup
t.Log("unique ID provided by singleton instance")
for i := 0; i < NumThreads; i++ {
wg.Add(1)
go func() {
defer wg.Done()
t.Logf("id:%v\n", si.GetUniqueId())
time.Sleep(time.Millisecond)
}()
}
wg.Wait()
t.Log("non-unique ID")
n := 100
for i := 0; i < NumThreads; i++ {
wg.Add(1)
go func() {
defer wg.Done()
t.Log("num:", n)
n++
time.Sleep(time.Millisecond)
}()
}
wg.Wait()
}
Loading…
Cancel
Save