朱莉娅@threads single

cre*_*ell 2 multithreading julia

Julia Threads 中是否有类似于singleOpenMP 中命令的东西,可以确保所有线程在特定代码块之前等待,然后仅在一个线程中执行该块?我有一个循环,它在一次对所有位置执行更新之前在线程之间分配力的计算,并且我找不到任何功能来在不终止循环的情况下实现此目的@threads

Prz*_*fel 5

您可以使用锁:

function f()
    l = Threads.SpinLock()
    x = 0
    Threads.@threads for i in 1:10^7
        Threads.lock(l)
        x += 1  # this block is executed only in one thread
        Threads.unlock(l)
    end
    return x
end
Run Code Online (Sandbox Code Playgroud)

请注意,该SpinLock机制专用于非阻塞代码(即仅进行计算,循环中没有 I/O)。如果涉及 I/OReentrantLock则应使用。