# L-13 MCS 572 Wed 8 Feb 2023 : mergesortmt.jl # Example from https://julialang.org/blog/2019/07/multithreading # At the command line, type # for n in 1 2 4 8; do JULIA_NUM_THREADS=$n julia mergesortmt.jl; done # to run with 1, 2, 4, and 8 threads. import Base.Threads.@spawn # sort the elements of `v` in place, from indices `lo` to `hi` inclusive """ Sorts the elements of v in place, from hi to lo. """ function psort!(v, lo::Int=1, hi::Int=length(v)) if lo >= hi return v end if hi - lo < 100000 # no multithreading sort!(view(v, lo:hi), alg = MergeSort) return v end mid = (lo+hi)>>>1 # find the midpoint # task to sort the first half starts half = @spawn psort!(v, lo, mid) # runs with the current call below psort!(v, mid+1, hi) # wait for the lower half to finish wait(half) temp = v[lo:mid] # workspace for merging i, k, j = 1, lo, mid+1 # merge the two sorted sub-arrays @inbounds while k < j <= hi if v[j] < temp[i] v[k] = v[j] j += 1 else v[k] = temp[i] i += 1 end k += 1 end @inbounds while k < j v[i] = temp[i] k += 1 i += 1 end return v end """ Calls the psort! once to avoid compilation overhead. """ function main() a = rand(100) b = copy(a) psort!(b) a = rand(20000000) b = copy(a) @time psort!(b) end main()