How to use the sync.WaitGroup to execute all the goroutine?

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

How to use the sync.WaitGroup to execute all the goroutine?

问题

目前我正在将所有的值推送到通道中,并从中读取并对其进行平方处理。
我想避免使用time.Sleep(2000 * time.Millisecond),因为它会阻塞程序执行2秒钟,而我希望每个goroutine都能处理并等待其执行,然后退出程序。我对golang有点生疏,所以现在问这个基本问题:(。有人可以帮我吗?

package main

import (
	"fmt"
	"sync"
	"time"
)

func doSquare(num int) int {
	return num * num
}

var wg sync.WaitGroup

func main() {

	wg.Add(1)
	st := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
	quit := make(chan bool)
	ch := make(chan int)
	go func() {
		for i := range st {
			ch <- i
		}
	}()

	go func() {
		for {
			select {
			case x := <-ch:
				fmt.Println(doSquare(x))
				// return

			case <-quit:
				wg.Done()
			default:
				// fmt.Println("---")
				// do something
			}
		}
	}()

	quit <- true

	wg.Wait()
	time.Sleep(2000 * time.Millisecond)
}

请注意,我只翻译了代码部分,其他内容不包括在内。

英文:

Currently I am pushing all the values to the channel and reading from it and doing the square of it.
I want to avoid using time.Sleep(2000 * time.Millisecond) since it's blocking the execution for 2 seconds instead I want every goroutine to process and wait for its execution and then exit the program. I just got out of touch with golang so asking this basic question now :(. Can anyone help me with this?

package main

import (
	&quot;fmt&quot;
	&quot;sync&quot;
	&quot;time&quot;
)

func doSquare(num int) int {
	return num * num
}

var wg sync.WaitGroup

func main() {

	wg.Add(1)
	st := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
	quit := make(chan bool)
	ch := make(chan int)
	go func() {
		for i := range st {
			ch &lt;- i
		}
	}()

	go func() {
		for {
			select {
			case x := &lt;-ch:
				fmt.Println(doSquare(x))
				// return

			case &lt;-quit:
				wg.Done()
			default:
				// fmt.Println(&quot;---&quot;)
				// do something
			}
		}
	}()

	quit &lt;- true

	wg.Wait()
	time.Sleep(2000 * time.Millisecond)
}

答案1

得分: 1

只需将quit <- true移动到第一个goroutine的末尾。

func main() {
    wg.Add(1)
    st := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
    quit := make(chan bool)
    ch := make(chan int)
    go func() {
        for i := range st {
            ch <- i
        }
        quit <- true
    }()

    go func() {
        for {
            select {
            case x := <-ch:
                fmt.Println(doSquare(x))
                // return

            case <-quit:
                wg.Done()
                return
            default:
                // fmt.Println("---")
                // do something
            }
        }
    }()

    wg.Wait()
}

这是另一种通过close(ch)来表示没有更多数据的方法。

func main() {
    st := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
    quit := make(chan bool)
    ch := make(chan int) // improve concurrency by `ch := make(chan int, 100)`
    go func() {
        for i := range st {
            ch <- i
        }
        close(ch)
    }()

    go func() {
        for x := range ch {
            fmt.Println(doSquare(x))
        }
        quit <- true
    }()

    <-quit
}
英文:

Just move quit &lt;- true to the end of the first goroutine

func main() {
    wg.Add(1)
    st := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
    quit := make(chan bool)
    ch := make(chan int)
    go func() {
        for i := range st {
            ch &lt;- i
        }
        quit &lt;- true
    }()

    go func() {
        for {
            select {
            case x := &lt;-ch:
                fmt.Println(doSquare(x))
                // return

            case &lt;-quit:
                wg.Done()
                return
            default:
                // fmt.Println(&quot;---&quot;)
                // do something
            }
        }
    }()

    wg.Wait()
}

This is another way to signal there is no more data by close(ch)

func main() {
    st := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
    quit := make(chan bool)
    ch := make(chan int) // improve concurrency by `ch := make(chan int, 100)`
    go func() {
        for i := range st {
            ch &lt;- i
        }
        close(ch)
    }()

    go func() {
        for x := range ch {
            fmt.Println(doSquare(x))
        }
        quit &lt;- true
    }()

    &lt;-quit
}

huangapple
  • 本文由 发表于 2023年4月27日 14:37:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/76117415.html
匿名

发表评论

匿名网友

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

确定