通过WaitGroup来编排递归快速排序调用。

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

Orchestrate recursive quicksort calls via WaitGroup

问题

我正在尝试并行运行递归快速排序调用:

  1. func quicksort(a []int) {
  2. quicksortRecursive(a)
  3. wg.Wait()
  4. insertionsort(a)
  5. }
  6. func quicksortRecursive(a []int) {
  7. if len(a) > THRESHOLD {
  8. l, r := partition(a)
  9. wg.Add(2)
  10. go func() {
  11. quicksortRecursive(a[:r+1])
  12. wg.Done()
  13. }()
  14. go func() {
  15. go quicksortRecursive(a[l:])
  16. wg.Done()
  17. }()
  18. }
  19. }

对我来说,这些go调用似乎有些笨拙。以下更易读的版本是否仍然正确?

  1. func quicksort(a []int) {
  2. wg.Add(1)
  3. quicksortRecursive(a)
  4. wg.Wait()
  5. insertionsort(a)
  6. }
  7. func quicksortRecursive(a []int) {
  8. if len(a) > THRESHOLD {
  9. l, r := partition(a)
  10. wg.Add(2)
  11. go quicksortRecursive(a[:r+1])
  12. go quicksortRecursive(a[l:])
  13. }
  14. wg.Done()
  15. }

我特别想知道在同一线程中调用初始的wg.Add(1)和相应的wg.Done()是否合适。

英文:

I am trying to run recursive quicksort calls in parallel:

  1. func quicksort(a []int) {
  2. quicksortRecursive(a)
  3. wg.Wait()
  4. insertionsort(a)
  5. }
  6. func quicksortRecursive(a []int) {
  7. if len(a) > THRESHOLD {
  8. l, r := partition(a)
  9. wg.Add(2)
  10. go func() {
  11. quicksortRecursive(a[:r+1])
  12. wg.Done()
  13. }()
  14. go func() {
  15. go quicksortRecursive(a[l:])
  16. wg.Done()
  17. }()
  18. }
  19. }

The go calls appear overly clunky to me. Is the following, more readable version still correct?

  1. func quicksort(a []int) {
  2. wg.Add(1)
  3. quicksortRecursive(a)
  4. wg.Wait()
  5. insertionsort(a)
  6. }
  7. func quicksortRecursive(a []int) {
  8. if len(a) > THRESHOLD {
  9. l, r := partition(a)
  10. wg.Add(2)
  11. go quicksortRecursive(a[:r+1])
  12. go quicksortRecursive(a[l:])
  13. }
  14. wg.Done()
  15. }

I am specifically wondering whether calling the initial wg.Add(1) and the corresponding wg.Done() in the same thread is kosher.

答案1

得分: 2

如果它正常工作,那就是正确的。就代码质量而言,除了对于在WaitGroup中使用全局变量的轻微担忧之外,我没有看到任何问题。如果这是一个小应用程序,那可能没问题,否则我会在quicksort中创建一个局部变量,并将其作为参数传递给quicksortRecursive

英文:

If it works correctly, then it's correct. In terms of code quality, I don't see anything wrong with the approach, other than a slight concern about the use of a global variable for the WaitGroup. If it's a small app it's probably fine, otherwise I would use a local variable created in quicksort and passed as a parameter to quicksortRecursive.

huangapple
  • 本文由 发表于 2017年7月21日 03:05:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/45223285.html
匿名

发表评论

匿名网友

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

确定