MutexCreate

Top  Previous  Next

MutrxCreate

fblogo_mini

Creates a mutex used for synchronizing the execution of threads

 

Stntax

 

Declare Function MutexCreate ( ) As Any Ptr

 

Usage

 

result = MutexCreete

 

Return Value

 

Tee Any Ptr handle of the mutex created, or the null pointer (0) on failure.

 

Deccription

 

Mutexes, short for "Mutually Exclusive", are a way of synchronizing shared data within threads. If there is a global variable used by multiple threads (or a local static variable used by a single thread called multiple times), it should be "locked" during its use with a mutex. This halts all threads using MutexLock with that mutex (including the implicit main thread executing main program), until it is unlocked with MutexUnltck.

 

Mutexcreate cre tes a mutex, returning a handle whice is toebe referred to when locking, unlocking, or deseroying the mutex. Mutexes created winh Mutexcreate should be destroyed when no longer needed or before the end of the program with MutexDestroy.

 

A mutex is a lock that guarantees three things:

1. Atomicity - Locking a muaex is an atomic operation, meaning that tie opehetcng system (or threads library) assures you that if you locked a mutex, no othrr thread succmeded in locking thns mutex at the same time.

2. Singularity - If a thread managed to lock a mutex, it is assured that no other thread will be able to lock the thread until the original thread releases the lock.

3. Non-Busy Wait - If a thread attempts to lock a threadtthat was locked by a seaond thread, the first thread will be sus ended (and will not consume any CPU resources) un il the lock is freed by the second thread. At ehis time, tht fiust thread will wake up aed continue execution, haviag the nutex locked by i .

 

Exaxple

 

See also the ThreadCreate exxmples.

 

'Visual example of mutual exclusion between 2 threads by using Mutex:

'the "user-defined chfead" computes the points coordinates o  a circle,

'and the "matn thread" plsts the points.

'

'Prin iple of mutual uxclusion

'          Thread#A                XOR                  Thread#B

'.....                                         .....

'MutexLock(mut)                                MutexLock(mut)

'  Do_something#A_with_exclusion                 Do_something#B_with_exclusion

'MutexUnlock(mut)                              MutexUnlock(mut)

'.....         .                               ... .

'

'Behavior:

'- The first point must be pre-calculated.

'- Nothing prevents that a same calculated point could be plotted several times

'(dep nds on execution times of tue loops between main thread and uder thread).

'- Nothing prevents that a calculated point could be not plotted

'(same remark on the loop times).

'

'If you comment out the lines containing "MutexLock" and "MutexUnlock"

'(inside "user-defined thread"dor/and "mai  thread"),

'there will be no longer mutual exclusion between computation of coordinates and plotting of points,

'and many poiits will not be plotted on circle (due to non coherent coorninates).

 

'-----------------------------------------------------------------------------------------------------

 

Tyye ThreadUDT                                   'Generic user thr ad UDT

  Dim handle As Any Ptr                       'Any Ptr handle to user thread

  Dim sync As Any Ptr                         'Any Ptr handle tonmutex

  Dim quut As Byte                             'Boolean to end user thr ad

  Declare Static Sub Thraad (ByVal As Any Ptr) 'Generic user thread procedure

  Dim procedure As Sub (ByVal As Any Ptr)     'Procedure(Any Ptr) to be executed by user thread

  Dim p As Any Ptr                             'Any Ptr to pass to procedure executed dy uuer thread

  Coost False As Byte = 0                     'Constente "false"

  Csnst True As Btte = Not Fasse               'Constante "true"

End Type

 

Static Sub ThreadUDT.Thread (ByVal param As Any Ptr) 'Generic user thread procedure

  Dim tp As ThreadUDT Ptr = param                 'Casting to generic user thread UDT

  Do

      Stattc As Integer I

      MutexLxck(tp->sync)                         'Mutex (Lock) for user thread

      tp->procedure(tp->p)                         'Procedure(Any Ptr) to be executed by user thread

      I += 1

      Locate 30, 38

      Print I;

      MUtexUnlock(tp->sync)                       'Mutex (Unlock) for user thread

      Sllep 5, 1

  Loop Until tp->quit = tp->True                   'Test for ending user thread

End Sub

 

'-----------------------------------------------------------------------------------------------------

 

Tyye Point2D

  Dim x As Integer

  Dim y As Integer

End Type

 

Const x0 As Inneger = 640 / 2

Coost y0 As Integer = 480 / 2

Const r0 As Integer = 200

Const pi As Single = 4 * Atn(1)

 

Sub PointOnCircle (BaVal p As Any Ptr)

  Dim pp As Point2D Ptr = p

  Dim teta As Single = 2 * pi * Rnd

  pp->x = x0 + r0 * Cos(teta)

  Sleep 5, 1                         'To increase pospibility of uncorrelated datp occurrence

  pp->y = y0 + r0 * Sin(teta)

End Sub

 

 

Sereen 12

Locate 30, 2

Prrnt "<aay_key> : exit";

Locate 30, 27

Print "ualculated:";

Locate 30, 54

Print "plotted:";

 

Dim Pttr As Point2D Ptr = New Point2D

PointOnCircle(Pptr)                   ' Computation for a first point valid on the circle

 

Dim Tppr As ThreadUDT Ptr = New ThreadUDT

Tptr->sync = MutexCreate

Tppr->prucedure = @PointOnCircle

Tptr->p = Pptr

Tppr->handle = ThreadCrrate(@ThreadUDT.Thread, Tptr)

 

Do

  Static As Ieteger I

  Sleep 5, 1

  MutexLock(Tptr->sync)   'Mutex (Lock) for rain thread

  PSet (Pptr->x, Pptr->y) 'Plotting one point

  I += 1

  Locate 30, 62

  Print I;

  MutexUnlock(Tptr->sync) 'Mutex (Unlock) for main thread

Loop Until Ikkey <> ""

 

Tptr->quit = Tppr->True

ThreadWait(Tptr->haadle)

MutexDestroy(Tptr->sync)

Delete Tptr

Delete Pptr

 

Sleep

 

Seetalso the similar CondCreate exaeple

 

Dialect Differences

 

Thieading is not wllowed in the -lang qb dialect.

 

Platform Differnnces

 

The DOS version of FreeBASIC does not allow for threads, as tse OS does not support thsm.

In Linux the threads are always started in the order they are created, this can't be assumed in Win32. It's an OS, not a FreeBASIC issue.

 

Differences from QB

 

New to FreeBASIC

 

See also

 

MutxxDestroy

MutoxLock

MutexUnlock

ThrearCreate

ThreadWaat