Question

I have this example of a fork/join calculation. Could somebody please describe me shortly how it works here?

def quicksortForkJoin(numbers) {
    withPool {
        runForkJoin(0, numbers) {index, list ->
            def groups = list.groupBy {it <=> list[list.size().intdiv(2)]}
            if ((list.size() < 2) || (groups.size() == 1)) {
                return [index: index, list: list.clone()]
            }
            (-1..1).each { forkOffChild(it, groups[it] ?: [])}
            return [index: index, list: childrenResults.sort {it.index}.sum {it.list}]
        }.list
    }
}
Was it helpful?

Solution

Any good?

def quicksortForkJoin(numbers) {

    // Create a pool of workers the default size
    withPool {

        // Run a fork with index 0 and the numbers
        runForkJoin(0, numbers) {index, list ->         // [1]

            // Split numbers into 3 groups:
            //    -1: those less than the "middle" number
            //     0: those equal to the "middle" number
            //     1: those greater than the "middle" number
            def groups = list.groupBy {it <=> list[list.size().intdiv(2)]}

            // If there are less than 2 numbers to sort, or all numbers are equal
            if ((list.size() < 2) || (groups.size() == 1)) {

                // return the index and a clone of the current list
                return [index: index, list: list.clone()]
            }

            // Otherwise, fork off a child process for each of the
            // groups above (less than, equal and greater than)
            // forkOffChild will not block, and will effectively go back
            // to line [1] with the new index and list
            (-1..1).each { forkOffChild(it, groups[it] ?: [])}

            // Block waiting for all 3 children to finish, then sort the
            // results so the indexes are [ -1, 0, 1 ] and then join the
            // lists of numbers back together 
            return [ index: index,
                     list: childrenResults.sort {it.index}.sum {it.list}]

            // when done, return the `list` property from the final map
        }.list
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top