英文:
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
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论