sync - skynocover/Wiki-for-GoLang GitHub Wiki

sync

非同步處理

import (
    "sync"
)

sync.WaitGroup



var wg sync.WaitGroup //建立一個等待的group

wg.Add(1) //增加一項任務
defer wg.Done() //完成一項任務, 建議使用defer確認程式執行完
wg.Wait()  //等待任務都完成,之後才繼續

sync.Mutex

type taccount struct {
	locker   *sync.Mutex
	Account  string `json:"account"`
}

this.locker.Lock() //上鎖
this.locker.Unlock() //解鎖
this.locker = &sync.Mutex{} //使用前要先宣告

sync.Map

var m *sync.Map  //全域宣告
var m = &sync.Map{} //宣告進m

v,ok := m.LoadOrStore(accounts[i],0)//載入或儲存,若已存在ok會回傳true,原本的值不會改變

m.Range(func(key interface{}, value interface{}) bool { //遍歷需要使用func
	account := key.(taccount)
	log.Println(fmt.Sprintf("%+v",account))
	return true //回傳true會繼續下一輪
})

sync.atomic

原子性確保非同步正確

import (
    "sync/atomic"
)

type Treceive struct {
	time uint64
}

func (this *Treceive)Add()uint64{
	return atomic.AddUint64(&this.time,1)
}

func (this *Treceive)Reset(){
	atomic.StoreUint64(&this.time,0)
}

func (this *Treceive)Time()uint64{
	return this.time
}