How to implement a semaphore?

I've got an action list that could be called from several other action lists that are run in parallel via an async action group. This action list figures out who needs to be sent an email after a build and adds it to a variable. If more than one parallel action list calls it at the same time, they'll wipe out the contents of the variable, so I need a way to make sure that only one thread can call the action list at a time (actually, they can call it at the same time, I just need to make sure that only one is in a certain section of the code at a time). Typically I'd want something like a semaphore, so that when a thread enters the action list it would check to see if another thread is already in it and wait until the first thread was done. but i'm having trouble figuring out how to do this in FinalBuilder.

I tried doing a "Wait for Variable" to see when a %Sema% variable was set to "Unlocked" and then immediately set the variable to "Locked" (and set it back to "Unlocked" when finished), but if two threads are waiting, they both start up when the variable gets set to "Unlocked" and both try to run at the same time. Something like an atomic "Test and Set Variable" action would be ideal.

Is there a better way to protect a section of code to prevent two parallel threads from executing it at the same time? It would really be useful.

Thanks,

  Keith Hearn

  Build/Release Engineer

  Devicescape, inc.

 

Hi Keith,

You’re right that there is no clear way to do mutual exclusion in FinalBuilder at the moment. We’ll investigate what we can add to support this.

Regards,

Angus

I haven’t tried this, but would using an action list parameter rather than a normal variable help? Perhaps action list parameters are each stored in their own local variable space, rather than in the global variable space?

Or, a way to create a semaphore might be to use a “lock” file on disk:

Action starts:
Copy file foo to “lock”, with “fail if file already exists”. Use options on the Runtime tab to make it keep trying until the file doesn’t exist.
-If it succeeds, do your processing. Then delete the file.

Hi Steve,

You’re right that creating files (Create Text File is adequate, you don’t need to use Copy) is one way to ensure mutual exclusion. We’d actually recommended this to people in the past, it totally slipped my mind. If you’re doing this, remember to Delete the file inside a Finally block so you don’t end up “locked out” :-).

Action list parameters are scoped to each individual instance of the action list, but this isn’t necessary helpful if you want to edit a shared project variable.

Regards,

Angus

Heh, didn’t know the Create Text File action existed. I always just use Write to Text File. I guess their functionality is pretty similar, except that Write to Text File can’t be made to fail if the file already exists.

Steve

Thanks, I’ll give the create text file a try.

Keith