要点:
- 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 TestGetInstance200
Three separate 2 well chamber slides were used in this experiment n 6 wells per condition
I couldn t believe how much valuable information there was about periods and hormones
Diagnostic tests are needed to diagnose heat stroke and assess the extent of vital organ dysfunction, including
Inhibition of migration and invasiveness of highly metastatic cancer cells The diet level soft, pureed, mechanical soft, or regular should be noted
Appointments were easy to make via phone or email and their response times were good