Tag value changed event synchronization

ignition79
#1

Some of my tags have their valueChanged event that executes a common piece of code: say that tags Tets1 and Test2 execute the same longTask routine when their values change. The longTask routine reads a tag value, say tag target, increments that value and writes the value back to the same tag:

def longTask(tagPath):
	val=system.tag.read("target").value
	time.sleep(1)
	system.tag.write("target",val+1)

If by chance more then one event occurs at the same time, they must synchronized, so that no one gets the same target value as another.
For that purpose I started off with the python threading module like this:

import time
import threading
lock=threading.Lock()

def longTask(tagPath):
	lock.acquire(True)
	val=system.tag.read("target").value
	time.sleep(1)
	system.tag.write("target",val+1)
	lock.release()

The revised code seems not to work at all!
Then I switched to java.util.concurrent.locks package and rewrote the code like this:

import time
from java.util.concurrent.locks import ReentrantLock
rlock=ReentrantLock()

def longTask(tagPath):
	
	rlock.lock()
	val=system.tag.read("target").value
	time.sleep(1)
	system.tag.write("target",val+1)
	rlock.unlock()

That last version seems to work perfectly.
Therefore my questions:

  • what is the best practice to synchronize valueChanged events?
  • why does python threading module seem not to work? Am I doing anything wrong with it?

Thanks in advance, regards

0 Likes

#2

I haven’t looked close, but I suspect it is an artifact of jython’s threads really being able to run concurrently, where python’s threads don’t–at least, not in the interpreter. In general, if both java and python offer a way to do something, use the java way in jython.

0 Likes

#3

Ok, thanks pturmel, I will go that way!

0 Likes