CreateMutex()

Syntax

Mutex = CreateMutex()
Description
Creates a new mutex object. The mutex is initially unlocked.

The main objective of the mutex functions is thread synchronization. They do not create too much overhead, but they only work within one program, not system-wide. A mutex is an object that can only be "owned" or locked by one thread at a time, so it is used to protect shared resources. Only the thread that has the mutex locked may access a certain file, memory area, ...
See LockMutex() and UnlockMutex() for locking/unlocking a mutex. @noparameter

Return value

The new mutext object, or zero if the mutex creation has failed.

Example

  ; Run this code once as it is. You will see that the lines printed are
  ; mixed from between the threads. Now uncomment the Mutex functions and
  ; the strings are printed in order, because only one thread at a time
  ; has the right to execute the printing functions.
  ;
  Procedure WithoutMutex(*Number)     
    Shared Mutex
    
    For a = 1 To 5      
      ;LockMutex(Mutex)    ; uncomment this to see the difference
    
      PrintN("Thread "+Str(*Number)+": Trying to print 5x in a row:")
      For b = 1 To 5
        Delay(50)
        PrintN("Thread "+Str(*Number)+" Line "+Str(b))
      Next b          
      
      ;UnlockMutex(Mutex) ; uncomment this to see the difference
    Next a    
  EndProcedure
  
  OpenConsole()
  Mutex = CreateMutex()
  
  thread1 = CreateThread(@WithoutMutex(), 1)
  Delay(25)
  thread2 = CreateThread(@WithoutMutex(), 2)
  Delay(25)
  thread3 = CreateThread(@WithoutMutex(), 3)
  
  WaitThread(thread1)
  WaitThread(thread2)
  WaitThread(thread3)
  
  Input()

Supported OS

All

Thread Index - CreateSemaphore() ->