| 1 |
package sorts |
| 2 |
|
| 3 |
import ( |
| 4 |
"runtime" |
| 5 |
"sort" |
| 6 |
"sync" |
| 7 |
) |
| 8 |
|
| 9 |
// helpers to coordinate parallel sorts |
| 10 |
|
| 11 |
type sortFunc func(sort.Interface, task, func(task)) |
| 12 |
|
| 13 |
// MaxProcs controls how many goroutines to start for large sorts. If 0, |
| 14 |
// GOMAXPROCS will be used; if 1, all sorts will be serial. |
| 15 |
var MaxProcs = 0 |
| 16 |
|
| 17 |
// minParallel is the size of the smallest collection we will try to sort in |
| 18 |
// parallel. |
| 19 |
var minParallel = 10000 |
| 20 |
|
| 21 |
// minOffload is the size of the smallest range that can be offloaded to |
| 22 |
// another goroutine. |
| 23 |
var minOffload = 127 |
| 24 |
|
| 25 |
// bufferRatio is how many sorting tasks to queue (buffer) up per |
| 26 |
// worker goroutine. |
| 27 |
var bufferRatio float32 = 1 |
| 28 |
|
| 29 |
// parallelSort calls the sorters with an asyncSort function that will hand |
| 30 |
// the task off to another goroutine when possible. |
| 31 |
func parallelSort(data sort.Interface, sorter sortFunc, initialTask task) { |
| 32 |
max := runtime.GOMAXPROCS(0) |
| 33 |
if MaxProcs > 0 && MaxProcs < max { |
| 34 |
max = MaxProcs |
| 35 |
} |
| 36 |
l := data.Len() |
| 37 |
if l < minParallel { |
| 38 |
max = 1 |
| 39 |
} |
| 40 |
|
| 41 |
var syncSort func(t task) |
| 42 |
syncSort = func(t task) { |
| 43 |
sorter(data, t, syncSort) |
| 44 |
} |
| 45 |
if max == 1 { |
| 46 |
syncSort(initialTask) |
| 47 |
return |
| 48 |
} |
| 49 |
|
| 50 |
wg := new(sync.WaitGroup) |
| 51 |
// buffer up one extra task to keep each cpu busy |
| 52 |
sorts := make(chan task, int(float32(max)*bufferRatio)) |
| 53 |
var asyncSort func(t task) |
| 54 |
asyncSort = func(t task) { |
| 55 |
if t.end-t.pos < minOffload { |
| 56 |
sorter(data, t, syncSort) |
| 57 |
return |
| 58 |
} |
| 59 |
wg.Add(1) |
| 60 |
select { |
| 61 |
case sorts <- t: |
| 62 |
default: |
| 63 |
sorter(data, t, asyncSort) |
| 64 |
wg.Done() |
| 65 |
} |
| 66 |
} |
| 67 |
doSortWork := func() { |
| 68 |
for task := range sorts { |
| 69 |
sorter(data, task, asyncSort) |
| 70 |
wg.Done() |
| 71 |
} |
| 72 |
} |
| 73 |
for i := 0; i < max; i++ { |
| 74 |
go doSortWork() |
| 75 |
} |
| 76 |
|
| 77 |
asyncSort(initialTask) |
| 78 |
|
| 79 |
wg.Wait() |
| 80 |
close(sorts) |
| 81 |
} |