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

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

Orchestrate recursive quicksort calls via WaitGroup

问题

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

func quicksort(a []int) {
    quicksortRecursive(a)
    wg.Wait()
    insertionsort(a)
}

func quicksortRecursive(a []int) {
    if len(a) > THRESHOLD {
        l, r := partition(a)
        wg.Add(2)
        go func() {
            quicksortRecursive(a[:r+1])
            wg.Done()
        }()
        go func() {
            go quicksortRecursive(a[l:])
            wg.Done()
        }()
    }
}

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

func quicksort(a []int) {
    wg.Add(1)
    quicksortRecursive(a)
    wg.Wait()
    insertionsort(a)
}

func quicksortRecursive(a []int) {
    if len(a) > THRESHOLD {
        l, r := partition(a)
        wg.Add(2)
        go quicksortRecursive(a[:r+1])
        go quicksortRecursive(a[l:])
    }
    wg.Done()
}

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

英文:

I am trying to run recursive quicksort calls in parallel:

func quicksort(a []int) {
	quicksortRecursive(a)
	wg.Wait()
	insertionsort(a)
}

func quicksortRecursive(a []int) {
	if len(a) > THRESHOLD {
		l, r := partition(a)
		wg.Add(2)
		go func() {
			quicksortRecursive(a[:r+1])
			wg.Done()
		}()
		go func() {
			go quicksortRecursive(a[l:])
			wg.Done()
		}()
	}
}

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

func quicksort(a []int) {
	wg.Add(1)
	quicksortRecursive(a)
	wg.Wait()
	insertionsort(a)
}

func quicksortRecursive(a []int) {
	if len(a) > THRESHOLD {
		l, r := partition(a)
		wg.Add(2)
		go quicksortRecursive(a[:r+1])
		go quicksortRecursive(a[l:])
	}
	wg.Done()
}

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:

确定