Is it safe declare lock as module constant?

I have created a package that uses a spin lock and I have declared this as module constant (example shown below). Since Julia compiles the package, it will declare the constant only once. Will this cause any unexpected issues? If it is safe, can I use Reentract Lock, Thread Condition in similar way?

module Test

import Base.Threads: SpinLock, lock, unlock, trylock, islocked, wait, notify
const spin_lock = SpinLock()

function f1()
    lock(spin_lock) do 
        # some work
    end
end

function f2()
    lock(spin_lock) do 
        # some work
    end
end
end

Yep, it works great! It’s a pretty common pattern among packages, from what I’ve seen.

1 Like

Can you share some package that uses lock in this way? Probably it will help me in following common practice

AMDGPU.jl: AMDGPU.jl/AMDGPU.jl at 43133cd2e83b66feb52fc8373cfcc0714dcd3810 · JuliaGPU/AMDGPU.jl · GitHub
Dagger.jl: Dagger.jl/Sch.jl at 0107b31ce422e5a4fa5b15ab873b34d4c07306f2 · JuliaParallel/Dagger.jl · GitHub

Neither of these are particularly simple packages, but for the most part, it works as you’d expect: the lock is global across the Julia process.

1 Like