0

Julia's multithreading system is built atop tasks. I can create an asynchronous task that will always run on the thread that spawned it with an @async. I can create a task that can be run on any thread with a Threads.@spawn. Or I can split up an entire for loop across all available threads using Threads.@threads for ....

How can I put a task onto a particular thread of my choosing — that's not the one that created it?

1 Answer 1

1

One way is to use ThreadPools.jl. It provides a @tspawnat macro that allows spawning a task on a specific thread.

Example: (taken from the package's README.md)

julia> t = @tspawnat 4 Threads.threadid()
Task (runnable) @0x0000000010743c70

julia> fetch(t)
4

The implementation of the macro can be found here.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! This package was born out of the real lack of this API in Base Julia itself; see issue #34267 for more details. Note that the macro's implementation can be used in an ad-hoc manner as well — it's really just a few lines of code. (You can ignore the whole if $(Expr(:islocal, var)) block as that's only needed if you want enclosing @sync macros to wait on the task; it's just the sticky change and the ccall.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.