Help with the locks

Hello guys! I am not able to make the example in the documentation about lock work.

cont = Int(0)
lk = ReentrantLock()
@threads for i in 1:100
    lock(lk)
    try
        cont +=1
    finally
        unlock(lk)
    end
end
print(cont)

I get the following error:

ERROR: TaskFailedException
Stacktrace:
 [1] wait
   @ ./task.jl:334 [inlined]
 [2] threading_run(func::Function)
   @ Base.Threads ./threadingconstructs.jl:38
 [3] top-level scope
   @ ./threadingconstructs.jl:97

    nested task error: UndefVarError: cont not defined
    Stacktrace:
     [1] macro expansion
       @ ~/Linkedin/proxy.jl:39 [inlined]
     [2] (::var"#3#threadsfor_fun#5"{UnitRange{Int64}})(onethread::Bool)
       @ Main ./threadingconstructs.jl:85
     [3] (::var"#3#threadsfor_fun#5"{UnitRange{Int64}})()
       @ Main ./threadingconstructs.jl:52

global cont += 1

2 Likes

It worked! Thank you.

For context why that worked, loops introduce their own scope for each iteration.

https://docs.julialang.org/en/v1/manual/variables-and-scoping/