一起学go开发:goroutine并发

在语言里有一种机制保证并发安全,即:goroutine,又叫:go程,先来看一段代码:

func Starter() {
	fmt.Println("This is the starter on call")
}

func Follow() {
	fmt.Println("This is the follower on call")
}

  

hello.Starter()
hello.Follow()

  在常规情况下,代码是按照函数的调用顺序执行的,但如果我们使用go程以后,又会怎样呢?

go hello.Starter()
hello.Follow()

  当使用go程以后,多次执行代码我们会发现函数的执行不再按照预期的顺序执行了,这就是所谓的并发。

  现在思考一下:如果要给Starter使用go程,同时还想保持先执行Starter函数,再执行Follow函数,该怎么实现呢?

  很庆幸的是,go的sync.WaitGroup机制可以帮我们实现这个需求,实现代码如下:

func Starter1(wg *sync.WaitGroup) {
	fmt.Println("This is the starter1 on call")
	defer wg.Done()
}

func Follow1() {
	fmt.Println("This is the follower1 on call")
}

  

	var wg sync.WaitGroup
	wg.Add(1)
	go hello.Starter1(&wg) // 使用sync.WaitGroup确保goroutine执行完成
	wg.Wait()
	hello.Follow1()

  sync.WaitGroup provides a goroutine synchronization mechanism in Golang, and is used for waiting for a collection of goroutines to finish.

  sync.WaitGroup机制用于保证一组goroutine执行完成。

 
 
 
 
 
posted @ 2023-03-11 22:30  jamstack  阅读(14)  评论(0编辑  收藏  举报