gpt4 book ai didi

julia - 如何在 Julia 函数中使用可选的线程

转载 作者:行者123 更新时间:2023-12-04 19:25:27 26 4
gpt4 key购买 nike

我有一个函数可以选择在其主循环中使用线程,当参数 usingthreads 时这样做是 true .目前,代码如下所示:

function dosomething(usingthreads::Bool)
n = 1000
if usingthreads
Threads.@threads for i = 1:n
#20 lines of code here
end
else
for i = 1:n
#same 20 lines of code repeated here
end
end
end

将“20 行”放在一个单独的函数中比上面的更不讨厌。还有其他方法吗?

最佳答案

您可以使用根据 Threads.nthreads() 的结果改变其行为的宏。 :

macro maybe_threaded(ex)
if Threads.nthreads() == 1
return esc(ex)
else
return esc(:(Threads.@threads $ex))
end
end

如果没有线程,这个宏将是一个空操作:
julia> @macroexpand @maybe_threaded for i in 1:5
print(i)
end
:(for i = 1:5
#= REPL[2]:2 =#
print(i)
end)

但是当启用线程时,例如 JULIA_NUM_THREADS=4它将扩展到线程版本:
julia>  @maybe_threaded for i in 1:5
print(i)
end
41325

编辑:重新阅读问题后,我意识到这并没有真正回答它,但无论如何它可能有用。

关于julia - 如何在 Julia 函数中使用可选的线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58580436/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com