Mutex

A mutex object is a synchronization object whose state is set to signaled when it is not owned by any thread and non-signaled when it is owned. Its name comes from its usefulness in coordinating mutually exclusive access to a shared resource. Only one thread at a time can own a mutex object. However, mutexes can be shared by threads from multiple processes.

For example, to prevent two threads from writing to shared memory at the same time, each thread waits for ownership of a mutex object before executing the code that accesses the memory. After writing to the shared memory, the thread releases the mutex object.

A thread calls the CreateMutex function to create a mutex object. The creating thread can request immediate ownership of the mutex object as well as specify a name for the mutex object. When a thread finishes whatever task the mutex synchronizes, it can release the mutex and the mutex will revert to an signalled state. Other threads can use a wait function, such as WaitForSingleObject, to learn when the mutex object has been relinquished, and can then come in and request ownership of the mutex. Threads that are waiting for ownership of the mutex are placed in a first in, first out queue; the first thread to wait on the mutex will be the first to receive ownership of the mutex, regardless of thread priority.

Code Sample

! demonstrates how to use mutex

mt=CreateObject("AMutex")

if mt=Nothing

TestStatus=FAIL

ExitTest

endif

s=""

mt.Lock()

hThread=CreateThread(StringConcatThread, 100)

if hThread=0 then

TestStatus=FAIL

ExitTest

endif

! test if thread was completed

if WaitForSingleObject(hThread, 1000)<>awaitObject0

TestStatus=FAIL

endif

mt.Unlock()

if s<>"" then

TestStatus=FAIL

endif

mt=Nothing