TutMutexCreateFast create a high-performance mutex object
initial_state
TRUE if mutex is to be initially locked
Mutex object if successful, T_INVALID_MUTEX otherwise.
If TutMutexCreateFast fails, it returns T_INVALID_MUTEX, and sets the global C error number.
TutMutexCreateFast creates a mutex object much the same as TutMutexCreate does, but with several important differences:
To lock these mutex objects, call TutMutexLockFast or TutMutexLock with the special timeout value of 0.0
. TutMutexLockFast blocks until the mutex can be acquired. TutMutexLock with timeout of 0.0
makes a single attempt to acquire the mutex, and if it is not available, returns FALSE without blocking.
If your application needs recursive mutexes, use those created by TutMutexCreate. If speed is of primary importance, TutMutexCreateFast mutex objects may be a better choice.
Mutex objects created with TutMutexCreateFast cannot be recursively locked; attempts to do so result in deadlock. Ensure that only the thread owning the lock on a particular "fast" mutex attempts to unlock it. Unlocking a mutex held by another thread causes unpredictable behavior.
TutMutexCreate, TutMutexLock, TutMutexLockFast, TutMutexUnlock, TutMutexDestroy
This code creates several threads which all update global data, using a fast mutex for synchronization:
#include <rtworks/common.h> #include <rtworks/util.h> #define NTHREADS (4) #define DURATION (5.0) T_MUTEX fast_mutex; T_INT4 counter = 0; T_PTR thread_func( T_PTR arg ) { T_REAL8 end; T_INT4 local_hits = 0; T_BOOL lock; TutOut("Thread %d starting...\n", (T_INT4)arg); end = TutGetWallTime() + DURATION; while (TutGetWallTime() < end) { /* do some calculation, I/O, etc. */ lock = TutMutexLockFast(fast_mutex); if (!lock) { TutOut("Could not lock mutex!\n"); break; } ++counter; ++local_hits; if (!TutMutexUnlock(fast_mutex)) { TutOut("Could not unlock mutex!\n"); break; } TutSleep(0.1); } TutThreadExit((T_PTR)local_hits); } /* thread_func */ int main( void ) { T_THREAD threads[NTHREADS]; T_INT4 count; fast_mutex = TutMutexCreateFast(TRUE); if (T_INVALID_MUTEX == fast_mutex) { TutOut("Cannot create fast mutex!\n"); TutExit(1); } TutOut("Creating %d threads...\n", NTHREADS); for (count=0; count<NTHREADS; count++) { threads[count] = TutThreadCreate(thread_func, (T_PTR)(count+1), NULL); if (TutThreadEqual(threads[count], T_INVALID_THREAD)) { TutOut("Can’t start thread %d!\n", count); TutExit(2); } } TutOut("Releasing threads...\n"); TutMutexUnlock(fast_mutex); for (count=0; count<NTHREADS; count++) { T_PTR result; if (TutThreadWait(threads[count], &result)) { TutOut("Thread %d exited, contributing %d hits.\n", count+1, (T_INT4)result); } } TutOut("In total, the counter was hit %d times.\n", counter); } /* main */
TIBCO SmartSockets™ Utilities Software Release 6.8, July 2006 Copyright © TIBCO Software Inc. All rights reserved www.tibco.com |