I am new to Go and I am trying to understand it a bit better, especially talking about goroutines.
I've found a parallel MergeSort algorithm on GitHub and while I am investigating this code, I've got some questions, I want to understand why is it used and is there any way to convert it to other types.
First question, why the channel is used as struct{}
instead of int[]
or something else? Is there any way to change that to int[]
or any other type?
Other question would be, why this algorithm uses go func()
instead of creating new function for that? Is there a way to implement it with other function and simply writing go
keyword before?
And the last question, when default
case is being used?
func MultiMergeSortWithSem(data []int, sem chan struct{}) []int {
if len(data) < 2 {
return data
}
middle := len(data) / 2
var waitGroup sync.WaitGroup
waitGroup.Add(2)
var leftData []int
var rightData []int
select {
case sem <- struct{}{}:
go func() {
leftData = MultiMergeSortWithSem(data[:middle], sem)
<-sem
waitGroup.Done()
}()
default:
leftData = SingleMergeSort(data[:middle])
waitGroup.Done()
}
select {
case sem <- struct{}{}:
go func() {
rightData = MultiMergeSortWithSem(data[middle:], sem)
<-sem
waitGroup.Done()
}()
default:
rightData = SingleMergeSort(data[middle:])
waitGroup.Done()
}
waitGroup.Wait()
return Merge(leftData, rightData)
}