// Goroutine基本使用funcprintNumbers(){for i :=1; i <=5; i++{time.Sleep(100* time.Millisecond)fmt.Printf("数字:%d\n", i)}}funcprintLetters(){for i :='a'; i <='e'; i++{time.Sleep(150* time.Millisecond)fmt.Printf("字母:%c\n", i)}}funcmain(){goprintNumbers()goprintLetters()// 等待goroutine执行time.Sleep(time.Second)}
type SafeCounter struct{mu sync.Mutexcounter int}func(c *SafeCounter)Increment(){c.mu.Lock()defer c.mu.Unlock()c.counter++}func(c *SafeCounter)Value()int{c.mu.Lock()defer c.mu.Unlock()return c.counter
}funcmain(){counter :=&SafeCounter{}for i :=0; i <1000; i++{go counter.Increment()}time.Sleep(time.Second)fmt.Println(counter.Value())}
6.4.2 读写锁
type Cache struct{mu sync.RWMutexdata map[string]int}func(c *Cache)Read(key string)(int,bool){c.mu.RLock()defer c.mu.RUnlock()value, ok := c.data[key]return value, ok
}func(c *Cache)Write(key string, value int){c.mu.Lock()defer c.mu.Unlock()c.data[key]= value
}
6.4.3 原子操作
var counter int64funcincrementCounter(){atomic.AddInt64(&counter,1)}funcgetCounter()int64{return atomic.LoadInt64(&counter)}