Skip to content

Commit

Permalink
safer handling of active worker count
Browse files Browse the repository at this point in the history
  • Loading branch information
skelterjohn committed Oct 4, 2012
1 parent f294020 commit 551fc68
Showing 1 changed file with 9 additions and 4 deletions.
13 changes: 9 additions & 4 deletions mergesort/mergesort.go
Expand Up @@ -59,7 +59,7 @@ func OverlyConcurrentMergeSort(data []int) {
Merge(data, left, right)
}

func ConcurrentPivotMergeSort(data []int) {
func SlightlyConcurrentMergeSort(data []int) {
var activeWorkers int32
var aux func([]int)
aux = func(data []int) {
Expand All @@ -71,7 +71,9 @@ func ConcurrentPivotMergeSort(data []int) {
left := append([]int{}, data[:pivot]...)
right := append([]int{}, data[pivot:]...)

if atomic.LoadInt32(&activeWorkers) < int32(runtime.NumCPU()) && atomic.CompareAndSwapInt32(&activeWorkers, activeWorkers, activeWorkers+1) {
curActiveWorkers := atomic.LoadInt32(&activeWorkers)

if curActiveWorkers < int32(runtime.NumCPU()) && atomic.CompareAndSwapInt32(&activeWorkers, curActiveWorkers, curActiveWorkers+1) {

var wg sync.WaitGroup
wg.Add(1)
Expand All @@ -86,6 +88,9 @@ func ConcurrentPivotMergeSort(data []int) {
MergeSort(right)
}
Merge(data, left, right)

curActiveWorkers = atomic.LoadInt32(&activeWorkers)
atomic.CompareAndSwapInt32(&activeWorkers, curActiveWorkers, curActiveWorkers-1)
}
aux(data)
}
Expand Down Expand Up @@ -117,8 +122,8 @@ func TimingTest(name string, data []int, merger func([]int)) {

func main() {
runtime.GOMAXPROCS(runtime.NumCPU())
data := make([]int, 1e5)
data := make([]int, 5e5)
TimingTest("Normal", data, MergeSort)
TimingTest("Overly concurrent", data, OverlyConcurrentMergeSort)
TimingTest("Slightly concurrent", data, ConcurrentPivotMergeSort)
TimingTest("Slightly concurrent", data, SlightlyConcurrentMergeSort)
}

0 comments on commit 551fc68

Please sign in to comment.