Using Semaphore Locks to Pause a Macro Until Another Macro Finishes Executing

I have a macro that launches several other macros asynchronously, does some more things, then I want to pause until those other macros are done executing.

I looked at the macro condition on Pause Until but it doesn't cover running/not running macros just active/inactive or enabled/disabled. I might be able to do it with one of the %ExecutingMacro% tokens and a big loop, but then I found semaphore locks.

I wasn't sure Semaphore Locks would do what I want but after testing these are perfect for this. The wiki page suggests that Semphore Locks are a way to prevent a new macro from launching until the lock is cleared, but it actually prevents the macro from moving to the next action until the lock is cleared.

This is what I do in a macro called MainMacro

  • MainMacro Executes macro1 asynchronously
    • This macro sets a semaphore lock with Name1
  • MainMacro Executes macro2 asynchronously
    • This macro sets a semaphor lock with Name2
  • MainMacro does a bunch of other stuff
  • MainMacro sets Semaphore Lock Name1
    • Macro will now pause until semaphore lock Name1 is cleared
  • MainMacro sets Semaphore Lock Name2
    • Macro will now pause until semaphore lock Name2 is cleared
  • MainMacro continues confident that both Macro1 and Macro2 are done

Suggestions:
Not sure this would make a good addition to the wiki, but the current article emphasizes "not executing another macro until lock clears" instead of "pausing macro until lock clears". Might be a good additional use case to add.

Correction:
The semaphore lock page has this:

The normal case is that all triggered macros run simultaneously (or synchronously),

I believe (or synchronously) is incorrect and it should be (or asynchronously). Sequential execution rather than simultaneous would be synchronously.

@peternlewis?

Rewritten as:

Although it is rare to have multiple macros triggered at the same time, the normal behaviour in Keyboard Maestro is that all triggered macros run simultaneously, with actions from each independently triggered macro running at the same time.

Most macros are triggered explicitly manually, and typically the user waits for them to complete before they trigger another macro. So macros triggered like this will rarely run at the same time.

4 Likes