我想在单独的核心上运行一个函数。我编写了一个脚本,可以异步并行运行两次。
const results = Channel()
function my_function()
delay = rand() * 5
@info "Task with $delay s"
@info "Thread $(Threads.threadid())"
sleep(delay)
put!(results, delay)
end
errormonitor(@async my_function())
errormonitor(@async my_function())
@info "returned $(take!(results))"
@info "returned $(take!(results))"
Run Code Online (Sandbox Code Playgroud)
但两次都在同一个线程中。
[ Info: Task with 2.9497522378270298 s
[ Info: Task with 4.956428193185428 s
[ Info: Thread 1
[ Info: Thread 1
[ Info: returned 2.9497522378270298
[ Info: returned 4.956428193185428
Run Code Online (Sandbox Code Playgroud)
如何my_function在不同的线程上运行?
@async任务在调度它们的线程上运行(示例中的线程 1)。要在线程上生成任务,请使用Threads.@spawn(并确保使用多个线程启动 Julia):
$ cat main.jl
const results = Channel()
function my_function()
delay = rand() * 5
@info "Task with $delay s running on thread $(Threads.threadid())"
sleep(delay)
put!(results, delay)
end
Threads.@spawn my_function()
Threads.@spawn my_function()
@info "returned $(take!(results))"
@info "returned $(take!(results))"
$ julia --threads=auto main.jl
[ Info: Task with 0.3894362661856865 s running on thread 2
[ Info: Task with 1.4960360211694967 s running on thread 4
[ Info: returned 0.3894362661856865
[ Info: returned 1.4960360211694967
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
886 次 |
| 最近记录: |