要点:
sync.Once 的应用
高并发场景下读写锁
package singleton import "sync" var ( p *Pet once sync.Once ) func init(){ once.Do( func() { p = &Pet{} }) } func GetInstance() *Pet{ return p } type Pet struct { Name string Age int m sync.Mutex } func (p *Pet)GetName()string{ return p.Name } func (p *Pet) GetAge() int{ return p.Age } func(p *Pet) SetName(name string) { p.m.Lock() defer p.m.Unlock() p.Name = name } func(p *Pet) IncAge() { p.m.Lock() defer p.m.Unlock() p.Age++ }
测试用例
package singleton import "testing" func TestGetInstance(t *testing.T) { p := GetInstance() p.SetName("tommy") p.IncAge() p.GetName() p.GetAge() }
测试并发场景
func IncAgeTest1(){ p = GetInstance() p.IncAge() } func IncAgeTest2(){ p = GetInstance() p.IncAge() }
package singleton import ( "fmt" "sync" "testing" ) func TestGetInstance(t *testing.T) { wg := sync.WaitGroup{} wg.Add(200) for i:=0;i<100;i++{ go func() { defer wg.Done() IncAgeTest1() }() go func() { defer wg.Done() IncAgeTest2() }() } wg.Wait() p := GetInstance() fmt.Println(p.Age) }
// output === RUN TestGetInstance 200
有疑问加站长微信联系(非本文作者)