# Issue with \`@lock\`

**URL:** <https://discourse.julialang.org/t/issue-with-lock/135302>\
**Category:** General Usage\
**Tags:** question\
**Created:** [January 28, 2026, 12:09am UTC](https://discourse.julialang.org/t/issue-with-lock/135302 "2026-01-28T00:09:05Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![WalterMadelim](https://avatars.discourse-cdn.com/v4/letter/w/3e96dc/32.png) [@WalterMadelim](https://discourse.julialang.org/u/WalterMadelim)\
**Post date:** [January 28, 2026, 12:09am UTC](https://discourse.julialang.org/t/issue-with-lock/135302/1 "2026-01-28T00:09:05Z")

</div>

```julia-auto
help?> @lock
  @lock l expr

  Macro version of lock(f, l::AbstractLock) but with expr instead of f function. Expands
  to:

  lock(l)
  try
      expr
  finally
      unlock(l)
  end

```

I’m not sure if this is a bug.

```julia-auto
julia> r = Ref(0);

julia> x = r[]
0

julia> x
0

julia> l = ReentrantLock()
ReentrantLock() (unlocked)

julia> @lock(l, y = r[])
0

julia> y
ERROR: UndefVarError: `y` not defined in `Main`

```

---

<div class="post-metadata">

**Author:** ![odow](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/odow/32/28685_2.png) [@odow](https://discourse.julialang.org/u/odow)\
**Post date:** [January 28, 2026, 12:12am UTC](https://discourse.julialang.org/t/issue-with-lock/135302/2 "2026-01-28T00:12:43Z")

</div>

Not a bug. It does what it says:

```Julia
julia> r = Ref(0);

julia> x = r[]
0

julia> x
0

julia> l = ReentrantLock()
ReentrantLock() (unlocked)

julia> lock(l)

julia> try
           y = r[]
       finally
           unlock(l)
       end
0

julia> y
ERROR: UndefVarError: `y` not defined in `Main`
Suggestion: check for spelling errors or missing imports.

```

You need

```Julia
julia> y = @lock(l, r[])
0

```

---

<div class="post-metadata">

**Author:** ![odow](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/odow/32/28685_2.png) [@odow](https://discourse.julialang.org/u/odow)\
**Post date:** [January 28, 2026, 12:20am UTC](https://discourse.julialang.org/t/issue-with-lock/135302/3 "2026-01-28T00:20:50Z")

</div>

I think the lesson is that scopes and macros are tricky. It’s yet another reason why macros should be used as infrequently as possible.
