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

Phi*_*ell 5 julia

我有一个函数,可以选择在其主循环中使用线程,而当参数为时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
Run Code Online (Sandbox Code Playgroud)

比上面更讨厌的是将“ 20行”放在单独的函数中。还有另一种方法吗?

Kri*_*son 4

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

macro maybe_threaded(ex)
    if Threads.nthreads() == 1
        return esc(ex)
    else
        return esc(:(Threads.@threads $ex))
    end
end
Run Code Online (Sandbox Code Playgroud)

如果没有线程,这个宏将是空操作:

julia> @macroexpand @maybe_threaded for i in 1:5
           print(i)
       end
:(for i = 1:5
      #= REPL[2]:2 =#
      print(i)
  end)
Run Code Online (Sandbox Code Playgroud)

但是当启用线程时,JULIA_NUM_THREADS=4它将扩展到线程版本:

julia>  @maybe_threaded for i in 1:5
           print(i)
       end
41325
Run Code Online (Sandbox Code Playgroud)

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