Race Condition between memory tags

Hello,

I came across a race condition working on one of my project.
I have a memory say Quantity.
And I have two opc tags Amount1 and Amount2 subtract the value from Quantity and write the result back to Quantity.
Amount1 and Amount2 race for reading the current value of Quantity and I end up getting unexpected values.

A simple way to avoid this I thought, was to create a expression tag that sums up Amount1 and Amount2 and then subtract the sum from Quantity.
However, expression tags do not evaluate if the either of Amount1 or Amount2 doesn’t change.
I have instances where the new value for both Amount1 and Amount2 is the same as previous and want to accommodate for such scenarios.

Any advise on how to resolve this?

1 Like

You are probably going to have to restructure your application to carry Amount1 and Amount2 in messages, not tags, and perform the math in a mutex-protected script critical section. Tags do not carry any state that would reflect whether their value has been applied to another value (Quantity) yet or not.

1 Like

Found it very interesting and learnt something very important from your post. May be this can help.

Another possibility would be to use another “event” OPC item for each amount that would signal when that amount is new (tag change script), then process the corresponding amount. In this case, you would use system.opc.readValue for the amount to ensure that you receive it after the event item. I would also maintain the quantity in a python module global dictionary, such that it is only ever read from the memory tag when the script module is reloaded. After that, read and add use that python variable protected by mutex, and the new value is written back to the memory tag.