TryLockMutex()

Syntax

Result = TryLockMutex(Mutex)
Description
Tries to lock the specified mutex. Unlike LockMutex(), this function does not stop execution until the mutex is available. It returns immediately and the return-value indicates if the lock was successful or not. This is useful in situations were the thread should not wait for the mutex to be available but rather do other things in the meantime.

Parameters

Mutex The mutex to lock.

Return value

Nonzero if the mutex was successfully locked, zero otherwise.

Remarks

If the lock was successful, the UnlockMutex() function must be called to make the mutex available to other threads again. If this is not done, this could easily lead to a lockup situation.

Example

  Procedure ThreadProcedure(*Value)
    Shared Mutex
    
    Repeat
      If TryLockMutex(Mutex)
        PrintN("Mutex successfully locked.")
        
        UnlockMutex(Mutex)
        Break ; quit the loop and thread
      Else
        PrintN("Still waiting for mutex access...")
        Delay(200)
      EndIf
    ForEver  
  EndProcedure
  
  OpenConsole()
  
  Mutex = CreateMutex()
  LockMutex(Mutex) ; main program has the mutex locked at first
  Thread = CreateThread(@ThreadProcedure(), 0)
  
  Delay(4000)
  UnlockMutex(Mutex) ; now release the mutex, so the thread can get it
  
  Input()

See Also

UnlockMutex()

Supported OS

All

<- ThreadPriority() - Thread Index - TrySemaphore() ->