Lightweight tasks, Julia vs Elixir/OTP

Now in concluding this journey, I provide the following function for executing functions on specified threads:

function onthread(f::F, id::Int) where {F<:Function}
    t = Task(nothing)
    @assert id in 1:nthreads() "thread $id not available!"
    @threads for i in 1:nthreads()
        if i == id
            t = @async f()
        end
    end
    fetch(t)
end

Anyone having single threaded applications involving tasks can speed things up with it. With the above (contrived) example you can do

julia> @btime machin_series(10_000, handover=true)
  158.559 ms (10000 allocations: 156.25 KiB)
3.1414926535900345

julia> @btime onthread(2) do; machin_series(10_000, handover=true); end
  2.467 ms (10045 allocations: 160.48 KiB)
3.1414926535900345

More realistically I still get dramatic speedups of my simulation benchmarks with this:

date channel [ms] dice [ms] heating [ms] action [μs] comment
2020-02-20 42.431 296.433 59.631 38.156 before
2020-02-27 44.630 36.641 5.091 8.269 dice and heating onthread(2)

Maybe, now you can see why I went after this thing :slight_smile: .

You can just copy/paste onthread from above or get it from my repo by

] add "https://github.com/pbayer/ThreadingExperiments.jl"

julia> using ThreadingExperiments

Its compat is Julia 1.3. Maybe someone of you could test (by copying from this thread) if this thing works as well in Julia 1.2 and below.

3 Likes