LabWindows/CVI

cancel
Showing results for 
Search instead for 
Did you mean: 

Apply a thread lock to section of code

Hi,

I'm in the process of writing a program to take measurements from a Keithley picoammeter.  I have two threads that need to access the picoammeter and while it shouldn't happen at the same time, there is every chance it could.  I know this needs to be avoided so I've been trying to use CmtNewLock and CmtGetLock etc.  I have used it as follows:

    CmtGetLock (keithleyLock);    // get lock to prevent multiple use of the following code....
   
    totalDarkCurrent = 0.0;

    for (i=0; i<numberReadings; i++)
    {
        ibwrt (keithley6485, "G1X", strlen("G1X"));
        ibrd (keithley6485, singleDarkCurrent, 14);
        darkCurrentValue = atof (singleDarkCurrent);
   
        totalDarkCurrent = totalDarkCurrent + darkCurrentValue;
       
        Delay (PICOAMMETER_DELAY);
    }
   
    CmtReleaseLock (keithleyLock);    // release of code lock.

Is this a legal thing to do?  Should I locate the acquisition and release of the lock immediately around the ibrd function?  Is is ok to enclose a section of code?  Can anyone suggest a better way of doing this?

Many thanks,

Chris

0 Kudos
Message 1 of 4
(3,275 Views)

What your doing is legal but will block for the entire period in which the loop for (i=0; i<numberReadings; i++) is executing.  It is simple but not very efficient.   You would be better off if you set up your code to block only at the ibwrt and ibrd pair.

There are a number of links on cvi mulithreading at http://zone.ni.com/devzone/devzone.nsf/webcategories/FE30FBB1046AEFBE862567A900587DAC
in particular the link to Multithreading in LabWindows/CVI has a lot of good information on protecting variables and other issues you can run into when multithreading.

Good Luck

 

Message Edited by mvr on 07-20-2006 12:45 PM

0 Kudos
Message 2 of 4
(3,268 Views)
Great, thanks.  I had started to wonder if that would make more sense - I'm changed my code to reflect this now.

Chris


0 Kudos
Message 3 of 4
(3,263 Views)
When you implement the thread lock around the read to the meter, you will have to change your local variables to be thread safe as described in the document I referenced above. 
I don't know if this is a good fit for your application but if you have two threads that just need access to a recent measurement from the meter, it might be simpler to setup a thread off an async timer that reads the meter and places the latest value into a threadsafe variable or queue.  The other threads simply read the value as needed from the variable or queue.  This moves the lock/block functions around the variable and lets a single thread handle the meter.  The thread safe variables and async timer in cvi make this kind of design pretty simple to implement.  Thats just another possible way to go about implementing it, but whatever you feel most comfortable with is the way you should go.
0 Kudos
Message 4 of 4
(3,260 Views)