Interlock Objects with Integer

126 views Asked by At

I have a bunch of objects, and each object has an unique ID.

I need to interlock the objects so that only one of the objects are allowed to perform a certain operation at a time.

I got an idea to define an integer that all of the objects have access to.

If the interlock is free, the integer contains a zero. An object is then allowed to put its own unique ID into the integer, perform the operation and put back a zero afterwards.

If any other objects checks the integer while its locked it will see a non-zero value different from its own ID and back off.

It feels almost 100% certain that I'm reinventing an old principle here, but not being CS educated, I don't even know what it's called, so I don't know what to search for.

Is my approach to locking sound/flawed, and what should I be reading up on?

Note that this is fairly low level 61131-3/PLC-programming, so no Singleton patterns etc.

Thanks

2

There are 2 answers

0
pboedker On

Your description sounds a lot like the lock known from multi-process programming.

If you only use one process or PLC scan, your idea of using a common integer will work. Otherwise you will have to do a little more to prevent your objects from locking at the same time. Also you should add functionality in your program to get out of a deadlock, i.e. if an object makes a lock and never releases it again.

Here's Wiki's explanation of lock: https://en.wikipedia.org/wiki/Lock_(computer_science)

0
Jakob On

Using a lock is different depending on what PLC brand you are using, which you didn't mention. If you for instance use TwinCAT3 you can use "FB_IecCriticalSection", described here:

https://infosys.beckhoff.com/english.php?content=../content/1033/tc3_plc_intro/9007201580758155.html&id=7922950705104221030

More information on the topic (for TwinCAT): https://infosys.beckhoff.com/english.php?content=../content/1033/tc3_plc_intro/18014403093939979.html&id=3121411705348577788