Thread Lock Class Help
- Updated2023-02-21
- 2 minute(s) read
Thread Lock Class Help
This class contains functions you can use to create, acquire, release, and discard thread locksthread locks.
Call CmtNewLock at program initialization to create a lock for each set of data that you want to protect. This function returns a handle that you use to identify the lock in subsequent function calls. Before accessing the data or code protected by the lock, threads must call CmtGetLock to acquire the lock. After accessing the data, the threads must callCmtReleaseLock to release the lock. You can call CmtGetLock more than once from the same thread (it will not block on subsequent calls), but you must call CmtReleaseLock exactly once for each call that you make to CmtGetLock. CallCmtDiscardLock to free the lock resources before your program exits. The following code demonstrates how to use a LabWindows/CVI Utility Library lock to protect a global variable.
int lock;
int count;
int main (int argc, char *argv[])
{
int functionId;
CmtNewLock (NULL, 0, &lock);
CmtScheduleThreadPoolFunction (DEFAULT_THREAD_POOL_HANDLE, ThreadFunction, NULL, &functionId);
CmtGetLock (lock);
count++;
CmtReleaseLock (lock);
CmtWaitForThreadPoolFunctionCompletion (DEFAULT_THREAD_POOL_HANDLE, functionId, 0);
CmtDiscardLock (lock);
}
int CVICALLBACK ThreadFunction (void *functionData)
{
CmtGetLock(lock);
count++;
CmtReleaseLock(lock);
return 0;
}
![]() |
Note If you must protect global data that is shared across threads and you do not need to process messages while waiting for a lock, use the DefineThreadSafeScalarVar, DeclareThreadSafeScalarVar, DefineThreadSafeArrayVar, and DeclareThreadSafeArrayVar macros, which are defined in utility.h. |
A thread lock can either be named or unnamed. A named lock can be used across processes to synchronize multiple processes. You must pass a lock name to CmtNewLock to create a named lock. An unnamed lock cannot be used across processes.
You can create a thread lock that causes CmtGetLock to process messages while waiting for the lock to be released by another thread.
CmtGetLock and CmtReleaseLock are slower if you choose to process messages or name the lock.
Library: Utility Library