Go协程没有在运行。

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

Go goroutines are not running

问题

今天,我学习了关于"缓冲通道"的知识。我在理解中遇到的问题是,我正在使用WaitGroup的"Wait"函数来等待所有的goroutine执行完毕。

但是,并不是所有的goroutine都在执行,程序在等待所有的goroutine完成之前就结束了。

代码:

func main() {
	
	// 初始化一个WaitGroup
	var wg sync.WaitGroup

	// 向WaitGroup添加3个计数/缓冲
	wg.Add(3)
	
	fmt.Println("开始执行Goroutines")
	go responseSize("https://www.golangprograms.com", &wg)
	go responseSize("https://stackoverflow.com", &wg)
	go responseSize("https://coderwall.com", &wg)

	// 等待goroutines执行完毕
	wg.Wait()
	fmt.Println("主程序终止")

}

// 打印返回的响应体大小
func responseSize(url string, wg *sync.WaitGroup) {
	// 在goroutine完成时调用Done()方法
	defer wg.Done()

	fmt.Println("步骤1: ", url)
	response, err := http.Get(url)
	if err != nil {
		log.Fatal(err)
	}
	
	fmt.Println("步骤2: ", url)
	body, err := ioutil.ReadAll(response.Body)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println("步骤3: ", len(body))
}

我在这里漏掉了什么吗?

英文:

Today, I learned about buffered channels. The issue I am facing understanding is, I am using WaitGroup's Wait function for all the goroutines to execute.

But not all the goroutines are executing and the program ends before without waiting for all the goroutines to finish.

Code:

func main() {
	
	// initializing a WaitGroup
	var wg sync.WaitGroup

	// adding 3 counts/buffer to the WaitGroup
	wg.Add(3)
	
	fmt.Println("Start Goroutines")
	go responseSize("https://www.golangprograms.com", &wg)
	go responseSize("https://stackoverflow.com", &wg)
	go responseSize("https://coderwall.com", &wg)

	// wait for goroutines to finish
	wg.Wait()
	fmt.Println("Terminating the main program")

}

// just prints the response size of the body returned 
func responseSize(url string, wg *sync.WaitGroup) {
	// schedule the Done() call when the goroutine is finished
	wg.Done()

	fmt.Println("Step1: ", url)
	response, err := http.Get(url)
	if err != nil {
		log.Fatal(err)
	}
	
	fmt.Println("Step2: ", url)
	body, err := ioutil.ReadAll(response.Body)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println("Step3: ", len(body))
}

Am I missing something here?

答案1

得分: 5

使用defer wg.Done()代替wg.Done()。当前的写法是,你的goroutine在开始运行时就会发出工作已完成的信号,而不是在结束时发出信号,这样可以让主goroutine继续执行并退出。

英文:

Instead of

wg.Done()

use

defer wg.Done()

The way it is written, your goroutines signal that the work is gone when they start running, not when they end, allowing the main goroutine to continue and exit.

huangapple
  • 本文由 发表于 2021年8月20日 23:10:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/68864396.html
匿名

发表评论

匿名网友

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

确定