Critical Section

Critical section objects provide synchronization similar to that provided by mutex objects, except that critical section objects can be used only by the threads of a single process. Critical section objects provide a slightly faster, more efficient mechanism for mutual-exclusion synchronization than event, mutex, and semaphore objects. Unlike a mutex object, a critical section object can be owned by only one thread at a time, which makes it useful for protecting a shared resource from simultaneous access.

One type of situation where you might want to use a critical section is when you have a DMM and only one thread can use it at a time. In one thread, you want to measure AC, and in the other thread, you want to measure DC. However, the measurement takes some time; if the threads were not synchronized, one thread might set the DMM to return an AC reading, the second thread might then pop in to set the DMM to return a DC reading, and when the first thread returned, it might capture the DC value when it thought it was going to capture the AC value. You can use a critical section in this case to lock access to the DMM for the first thread, so it could make the setting and capture the appropriate resultant value undisturbed, and then let the second thread come in, make its setting, and capture its appropriate value.

Code Sample

! Thread-safe DMM

Procedure OnInit(): Void Public!Occurs when the driver is started.--------------------------------------------------------------------------------

{

csDMM=CreateObject("ACriticalSection")

if not csDMM then abort

}

Procedure OnEnd(): Void Public !Occurs before normal exiting of the application.

-------------------------------------------------------------------------------

{

csDMM=Nothing

}

Procedures

================================================================================

 

Procedure Measure_VAC(dVoltage): Void Public

--------------------------------------------------------------------------------

dVoltage: Var Double

{

csDMM.Lock()

Driver Set Function VAC

Driver Measure dVoltage

csDMM.Unlock()

}

Procedure Measure_maDC(dCurrent): Void Public

--------------------------------------------------------------------------------

dCurrent: Var Double

{

csDMM.Lock()

Driver Set Function maDC

Driver Measure dCurrent

csDMM.Unlock()

}

Variables

================================================================================

csDMM: ACriticalSection

END