Mutexes & Threading


I am trying to develop a code module that assigns a unique identity to something based on a barcode scan. Since there are multiple barcode readers I need make sure that only one event is firing at a time. I’m not exactly sure how threading works in ignition but here’s what I’m trying to do.

In the gateway startup events I’m defining a mutex that I will use later.


Then in a Gateway tag event I’m calling a code module that acquires the lock, does some work, then releases it. One note, we have only begun testing using a single gateway tag event per tag. Current testing is done simulating 5 barcode tags that can be written to at the same time (if not same time, very close to same time) However, I can’t seem to access the mutex set up in the gateway startup event in the code module.


for further detail, see attached pictures. Gateway tag events are roughly all the same but watch their own respective barcode tag. Each script under “MutexTestBar(x)” calls a code module within the project library that utilizes the paicMutex. At least thats what is being attempted

Is there somewhere else I should be creating the mutex or is there a better/different way to do this?



Okay I figured it out. Turns out I’m just new at Python and didn’t realize that variables in a given script are static. I just declared and initialized my mutex at the top of the script then everytime it gets called it’s the same instance of that mutex. No gateway scripts required. And now I’m getting the right output :slight_smile: .


I think this only works because of an implementation detail in how we compile and execute those scripts (and cache the compiled code).

The safer bet would be to store the mutex somewhere like system.util.getGlobals()

edit: I’m not super clear on where you’re defining each piece of code, maybe you can clear that up.

Awesome, that’s exactly what I was looking for. Thank you!

I edited the gateway startup script to the following:

My tag change script then reads from the global variable to acquire the lock. We have the same thing set up for 5 different tags and have something that sets all 5 at once to test the mutex.

I restarted the gateway to fire off the startup script and now the mutex works great without relying on implementation details :slight_smile:

Your locking will break whenever your project containing the script is saved, restarting it. If the lock is only protecting a resource in the same scope as the lock (top level of the script module), then it is safe anyways.

1 Like