Created
March 25, 2020 17:03
-
-
Save quinnj/40e989a28e3ee0138ff61d00b6d75313 to your computer and use it in GitHub Desktop.
Example of background thread workers for spawned tasks
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Workers | |
const WORK_QUEUE = Channel{Task}(0) | |
macro async(thunk) | |
esc(quote | |
tsk = @task $thunk | |
# the next line passes along task-local storage to the spawned task | |
# may not be desirable in all use-cases | |
tsk.storage = current_task().storage | |
put!(Workers.WORK_QUEUE, tsk) | |
tsk | |
end) | |
end | |
function init() | |
tids = Threads.nthreads() == 1 ? (1:1) : 2:Threads.nthreads() | |
Threads.@threads for tid in 1:Threads.nthreads() | |
if tid in tids | |
Base.@async begin | |
for task in WORK_QUEUE | |
schedule(task | |
wait(task) | |
end | |
end | |
end | |
end | |
return | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment