Calling Semaphore Lock twice in same Macro Thread?

@peternlewis - Let’s say I have two macros, MacroA and MacroB.

MacroA locks a Semaphore, then executes MacroB synchronously which also locks the same semaphore.

Here’s what I’m hoping is true (of course I can test this myself, but I wanted to hear it “officially” from you, so I know it’s unlikely to change, at least without release note comments):

  1. There’s no problem with locking the Semaphore multiple times in the same Macro Execution Thread.
  2. As you have stated frequently, Semaphores are automatically unlocked when a Macro Execution Thread terminates.
  • Assumption: This holds true, even if same Semaphore has been locked multiple times by the Macro Execution Thread.
  1. Therefore, my above scenario is just fine and dandy.

By the way, the reason I want to do this is that MacroB may also get called from places other than MacroA, so my logic can’t rely on the semaphore having already been locked by the executing macro thread.


PS to everyone else: This is one of the joys of multi-threaded programming. A Semaphore is like a Talking Stick, helping to make sure multiple concurrently executing macros don’t step on each other’s toes (to mix metaphores).

1 Like

Your assumptions are correct.

MacroB should both lock and then unlock the semaphore. It will not wait because the execution thread already holds a lock, and it will not release the semaphore because you still retain a lock that you have not unlocked.

If you don’t unlock it at the end of MacroB, then other macros that call MacroB will retain the semaphore until they exit which should be unnecessary - if it was necessary then they should have locked it themselves.

1 Like