Issue with `@lock`

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

Not a bug. It does what it says:

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> y = @lock(l, r[])
0
1 Like

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.

1 Like