Reputation: 125
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)
}
Upvotes: 0
Views: 94
Reputation: 10507
First question, why the channel is used as struct{} instead of int[] or something else?
struct{}
is often used as a type with channels when the actual type doesn't matter but instead the writing and reading from the channel do. So if you just need orchestration for some form of control, then sturct{}
is a solid choice as the data being passed can't possibly be useful.
Upvotes: 1