如何按特定顺序运行2个goroutine

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

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() {
  &lt;-ch
  func2()
}

Playground: https://go.dev/play/p/ZqHz-ILpA2J

EDIT: Following Paul Hankin's advice, using close(ch) instead of ch &lt;- 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 (
	&quot;fmt&quot;
	&quot;sync&quot;
)

func main() {

	var w sync.WaitGroup

	w.Add(1)
	go fun1(&amp;w)
	w.Wait()
	
	w.Add(1)
 	go	fun2(&amp;w)
	w.Wait()


}

func fun1(w *sync.WaitGroup) {
	i:=1000
	for i&gt;0{
		i-=1
	}
	fmt.Println(&quot;fun1&quot;)
	defer 	w.Done()
}

func fun2(w *sync.WaitGroup) {
	fmt.Println(&quot;fun2&quot;)
	defer w.Done()

}

huangapple
  • 本文由 发表于 2022年1月11日 01:13:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/70656333.html
匿名

发表评论

匿名网友

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

确定