英文:
How to run 2 goroutines in a specific order
问题
我想要按顺序执行两个 goroutine,一个接一个地执行。
例如,我在主函数中调用了以下的 goroutine:
go func1()
go func2()
我希望 func1() 先完成执行,然后才执行 func2(),每次运行主函数时都是这样。
如何实现在 goroutine 中的这种顺序?谢谢。
英文:
I want to execute 2 goroutines sequentially, one after another.
For example, I have following goroutines called in main function:
go func1()
go func2()
And I want that func1() should first complete its execution and then only func2() should execute, every time when I run my main function.
How can I achieve this ordering in goroutines?
Thanks.
答案1
得分: 7
为了确保函数的顺序执行,可以在一个 goroutine 中运行这些函数:
go func() {
func1()
func2()
}()
这样,func1() 和 func2() 将会按照顺序执行。
英文:
To ensure sequential execution of functions, run the functions in a single goroutine:
go func() {
func1()
func2()
}()
答案2
得分: 5
如果你真的想将它们作为单独的goroutine(为什么?),你需要对它们进行同步。你可以使用通道(channels)、互斥锁(mutexes)或其他并发原语。下面的示例使用一个信号通道来实现同步:
ch := make(chan struct{})
go func() {
func1()
close(ch)
}
go func() {
<-ch
func2()
}
Playground: https://go.dev/play/p/ZqHz-ILpA2J
编辑:根据Paul Hankin的建议,使用close(ch)
而不是ch <- struct{}{}
来表示完成。
英文:
If you really want them as separate goroutines (why?) you need to synchronize them. You can use channels, mutexes, or other concurrency primitives. The example below accomplishes that with a signaling channel:
ch := make(chan struct{})
go func() {
func1()
close(ch)
}
go func() {
<-ch
func2()
}
Playground: https://go.dev/play/p/ZqHz-ILpA2J
EDIT: Following Paul Hankin's advice, using close(ch)
instead of ch <- struct{}{}
to signal completion.
答案3
得分: 3
对于顺序运行的Go协程,你应该始终使用sync
包。
package main
import (
"fmt"
"sync"
)
func main() {
var w sync.WaitGroup
w.Add(1)
go fun1(&w)
w.Wait()
w.Add(1)
go fun2(&w)
w.Wait()
}
func fun1(w *sync.WaitGroup) {
i := 1000
for i > 0 {
i -= 1
}
fmt.Println("fun1")
defer w.Done()
}
func fun2(w *sync.WaitGroup) {
fmt.Println("fun2")
defer w.Done()
}
英文:
For squentially running go routine , you should always use sync
package
package main
import (
"fmt"
"sync"
)
func main() {
var w sync.WaitGroup
w.Add(1)
go fun1(&w)
w.Wait()
w.Add(1)
go fun2(&w)
w.Wait()
}
func fun1(w *sync.WaitGroup) {
i:=1000
for i>0{
i-=1
}
fmt.Println("fun1")
defer w.Done()
}
func fun2(w *sync.WaitGroup) {
fmt.Println("fun2")
defer w.Done()
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论