您的位置 首页 golang

Golang sync包的7件法宝

sync.WaitGroup

var g sync.WaitGroup

g.Add(1) //每创建一个goroutine,就把任务队列中任务的数量+1

g.Done() //任务完成,将任务队列中的任务数量-1,其实. Do ne就是.Add(-1)

g.Wait() //Wait()这里会发生阻塞,直到队列中所有的任务结束就会解除阻塞

sync.Mutex

mutex := sync.Mutex{};

mutex.Lock();

defer mutex.Unlock();

多个 线程 同时运行,获得Mutex锁者线程优先执行,其余线程阻塞等待

sync.RWMutex

rwMutex := sync.RWMutex{};

rwMutex.RLock();

defer rwMutex.RUnlock();

或者

rwMutex.Lock();

defer rwMutex.Unlock();

写请求在读锁和写锁时都必须阻塞等待,读请求只在写锁时阻塞等待

sync.Cond

Cond:条件变量

条件等待通过 Wait 让协程等待,通过 Signal 让一个等待的协程继续,通过 Broadcast 让所有等待的协程继续。

在 Wait 之前应当手动为 c.L 上锁,Wait 结束后手动解锁。为避免虚假唤醒,需要将 Wait 放到一个条件判断循环中。

func NewCond(l Locker) *Cond

func (c *Cond) Broadcast()

func (c *Cond) Signal()

func (c *Cond) Wait()

sync.Once

once := sync.Once{};

只执行一次以后不再触发

once.Do(func() {

fmt.Println(“Do once : “, idx); //这里只执行一次

})

sync. Map

sync.Map 线程安全 的map

syncMap.LoadOrStore()//如果没有则保存起来

syncMap.Load(idx);

sync.Pool

sync.Pool 线程安全对象池

p := &sync.Pool

p. Put (idx);

val := p.Get();

更多内容请关注每日编程,每天进步一点。

文章来源:智云一二三科技

文章标题:Golang sync包的7件法宝

文章地址:https://www.zhihuclub.com/94970.shtml

关于作者: 智云科技

热门文章

网站地图