Using The Lock() And Unlock() Functions For Multiple Threads On A Single Port


Recommended Posts

Greetings,

I am currently trying to read and write to a single port from multiple sequences. I jumped into the User Guide and decided that the Lock() and Unlock() functions would be perfect for me. However, when I proceed to set a local variable to the binary "Lock" indicator (Lock = Device.MyDevice.Lock()), it did not seem to show up in the drop down menu (which appears after I type in the "." after the device name). Is this binary function actually ".LockPort()"? Does this function lock the port and return a binary value at the same time? Thanks...

Link to comment
Share on other sites

The function is lockPort():

device.myDevice.LockPort()

It returns 1 if the port was locked by this function call and you can proceed, 0 if the port is already locked and you should not use the port. If the port is already locked, it will wait up until the timeout value for the port for it to become unlocked before returning 0. You can change this timeout value by passing a new, non-zero timeout value (in milliseconds) as a parameter to the function.

This isn't a hard lock. Its up to you to follow the return value of the lockPort() function. If it returns 1, go ahead and use the port. If it returns 0, you should not use the port. However, there is nothing keeping you from using the port anyway, nor is there anything forcing you to even call lockPort() from every thread.

Note that built in protocols like Modbus will honor LockPort() calls and perform the call internal themselves.

Note also that you probably should enclose everything between the lockport and unlockPort() in a try/catch block to ensure that unlockPort() gets called.

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.