# Help with the locks

**URL:** <https://discourse.julialang.org/t/help-with-the-locks/85692>\
**Category:** New to Julia\
**Created:** [August 13, 2022, 1:08am UTC](https://discourse.julialang.org/t/help-with-the-locks/85692 "2022-08-13T01:08:43Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![lucasmsoares96](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/lucasmsoares96/32/38743_2.png) [@lucasmsoares96](https://discourse.julialang.org/u/lucasmsoares96)\
**Post date:** [August 13, 2022, 1:08am UTC](https://discourse.julialang.org/t/help-with-the-locks/85692/1 "2022-08-13T01:08:43Z")

</div>

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

```julia
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:

```julia
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

```

---

<div class="post-metadata">

**Author:** ![jling](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/jling/32/212909_2.png) [@jling](https://discourse.julialang.org/u/jling)\
**Post date:** [August 13, 2022, 1:45am UTC](https://discourse.julialang.org/t/help-with-the-locks/85692/2 "2022-08-13T01:45:57Z")

</div>

> [@lucasmsoares96](#):
>
> ` cont +=1`

`global cont += 1`

---

<div class="post-metadata">

**Author:** ![lucasmsoares96](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/lucasmsoares96/32/38743_2.png) [@lucasmsoares96](https://discourse.julialang.org/u/lucasmsoares96)\
**Post date:** [August 13, 2022, 1:59am UTC](https://discourse.julialang.org/t/help-with-the-locks/85692/3 "2022-08-13T01:59:16Z")

</div>

It worked! Thank you.

---

<div class="post-metadata">

**Author:** ![Sukera](https://avatars.discourse-cdn.com/v4/letter/s/ce7236/32.png) [@Sukera](https://discourse.julialang.org/u/Sukera)\
**Post date:** [August 13, 2022, 4:35am UTC](https://discourse.julialang.org/t/help-with-the-locks/85692/4 "2022-08-13T04:35:26Z")

</div>

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

[https://docs.julialang.org/en/v1/manual/variables-and-scoping/](https://docs.julialang.org/en/v1/manual/variables-and-scoping/)
