问题标签 [goroutine]
For questions regarding programming in ECMAScript (JavaScript/JS) and its various dialects/implementations (excluding ActionScript). Note JavaScript is NOT the same as Java! Please include all relevant tags on your question; e.g., [node.js], [jquery], [json], [reactjs], [angular], [ember.js], [vue.js], [typescript], [svelte], etc.
for-loop - 有没有办法将 for 循环作为 go 例程运行而不将其放入单独的函数中
假设我想设置一个for循环运行但不想阻止执行,显然我可以将for循环放在一个函数中f
并调用go f
并继续我的生活,
但我很好奇是否有办法go for
直接调用, 就像是:
concurrency - Go语言中临界区的交替执行
我有两个套路:
确保这些例程中的关键部分始终交替执行的正确方法是什么?
换句话说,CS1 应该只在 CS2 之后执行,反之亦然:CS1、CS2、CS1、CS2、CS1 等。
go - 如何阻止程序/goroutine?
我有一个程序可以触发两个在后台提供服务的 goroutine。然后我想阻止主 goroutine 并让它们在后台运行。我想“永远”阻止,我不在乎干净的出口。我该怎么做?我可以在频道上等待,然后从不发送任何内容。我可以循环睡觉。两者都感觉不太对,我认为可能有一个更简单的block()
函数可以调用?
我目前正在这样做
go - sync.WaitGroup 的示例是否正确?
这个示例用法sync.WaitGroup
正确吗?它给出了预期的结果,但我不确定wg.Add(4)
和 的位置wg.Done()
。一次添加四个 goroutine 有意义wg.Add()
吗?
http://play.golang.org/p/ecvYHiie0P
结果(如预期):
go - gorouines 是否忽略通道的缓冲区大小
环境:OS X 10.8,Go 1.0.2
我创建了一个缓冲区大小为 2 的通道,然后如果我写入通道 3 次,它会抛出错误:
throw:所有的 goroutine 都处于休眠状态——死锁!
当然,这是正确的。
但是如果我在 goroutines 中写了四次或更多次通道,它工作正常,为什么?通道的容量是 2,为什么 goroutines 忽略了或者忘记了容量设置?我注释了读取通道代码,因此没有人会读取通道并节省容量。我也使用 time.Sleep 来等待所有 goroutine 完成它们的工作。
请查看以下代码: package main
有人可以打一些吗?多谢你们。
synchronization - What is go's preferred way to synchronize goroutines
I have an expensive function that I apply on all items of a slice. I'm using goroutines to deal with that, each goroutine dealing with one item of the slice.
The question is, as shown in the comment, what is the preferred way to wait all goroutines have done their job before calling the someValue
function ? Passing on a channel to performSlow
and waiting until everyone has written on it works, but it seems overkill :
Is there a better (i.e. more efficient and/or more idiomatic) way to do it ?
go - 处理 goroutine 时奇怪的事情
有两件奇怪的事情。
我在切片中制作了 1000 个数字,但它只打印 246,为什么是 246?为什么不是 1000?
如果我删除"log.Println("hey")"这一行,为什么它只打印0?
我知道它可能有同步问题,但我之前没有写过任何并发程序,所以有什么文章可以推荐吗?
recursion - 如何阻止(并加入)由未知数量的 goroutine 提供的频道?
我有一个递归函数。该函数将根据它获取的数据使用各种不同的值调用自身,因此递归的数量和深度是未知的:每次调用可能会调用自身零次或多次。该函数可以返回任意数量的值。
我想通过涉及 goroutine 和通道来并行化它。每个递归都inner
在自己的 goroutine 中运行,并在通道上发回一个值。外部函数处理这些值。
问题在于逃避结果通道循环。由于递归的“形状”(未知的数量和深度),我不能说“在n 个事件后完成”,也不能发送哨兵值。
我如何检测我的所有递归何时发生并从返回outer
?有没有更好的方法来解决这个问题?