sync.WaitGroup是Barrier的一种实现吗?

huangapple go评论77阅读模式
英文:

Is sync.WaitGroup an implementation of Barrier?

问题

在同步世界中,Barrier允许线程等待其他线程达到某个点。计数信号量允许n个线程访问共享资源。

因此,从这个角度来看,sync.WaitGroup是Barrier和计数信号量的结合(但没有共享资源的概念)。这个心智模型准确吗?

英文:

A Barrier in the synchronization world allows threads to wait for other threads to reach a certain point. A counting semaphore allows n numbers of threads to access a shared resource.

So from this, a sync.WaitGroup is a cross between a Barrier & a counting Semaphore (but without any concept of shared resource). Is this an accurate mental model ?

答案1

得分: 8

许多东西都可以用作障碍物。在Go语言中,最典型的障碍物是通道(channel)。如果你有多个goroutine需要等待,那么等待组(waitgroup)会很有用。

虽然等待组可以用作处理线程(goroutine)的障碍物,但它的功能不仅限于此。你可以将N个任务发送给M个goroutine,并让等待组跟踪任务的完成情况,而不是跟踪已完成的goroutine。

等待组的目的就是等待预期发生的事件数量。这可能是因为goroutine到达代码中的某个特定位置,任务完成了,或者只是因为你想等待。如果你将其视为一个简单的障碍物,那么你可能会限制它的用途。

英文:

Many things can be used as barriers. In go, the most idiomatic barrier is a channel. If you have more than one goroutine you are waiting for, then a waitgroup can be useful.

While a waitgroup can be used as a barrier dealing with threads (goroutines), that isn't all it can do. You could have N jobs sent to M goroutines and then have the waitgroup track jobs instead of goroutines that are finished.

The purpose of a waitgroup is simply to wait for the number of events you were expecting to occur. This could be because goroutines got to a certain place in the code, jobs were completed, or you just felt like it. If you have a mental model of it as just a barrier, it will limit your uses of it.

huangapple
  • 本文由 发表于 2014年3月28日 02:41:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/22696407.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定