Revision history for KeyPgMutexCreate


Revision [20985]

Last edited on 2016-03-13 04:47:40 by fxm [Formatting]

No Differences

Revision [20332]

Edited on 2016-02-10 16:03:07 by DkLwikki [Update link format]
Additions:
[[KeyPgDeclare|declare]] [[KeyPgFunction|function]] **Mutexcreate** ( ) [[KeyPgAs|as]] [[KeyPgAny|any]] [[KeyPgPtr|ptr]]
The ##[[KeyPgAny|any]] [[KeyPgPtr|ptr]]## handle of the mutex created, or the null pointer (0) on failure.
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 ##[[KeyPgMutexLock|Mutexlock]]## with that mutex (including the main thread executing main program), until it is unlocked with ##[[KeyPgMutexUnlock|Mutexunlock]]##.
##Mutexcreate## creates a mutex, returning a handle which is to be referred to when locking, unlocking, or destroying the mutex. Mutexes created with ##Mutexcreate## should be destroyed when no longer needed or before the end of the program with ##[[KeyPgMutexDestroy|Mutexdestroy]]##.
See also the ##[[KeyPgThreadCreate|Threadcreate]]## examples.
Static As Integer I
MutexLock(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
Sleep 5
See also the similar ##[[KeyPgCondCreate|Condcreate]]## example
- Threading is not allowed in the //[[CompilerOptlang|-lang qb]]// dialect.
- ##[[KeyPgMutexDestroy|Mutexdestroy]]##
- ##[[KeyPgMutexLock|Mutexlock]]##
- ##[[KeyPgMutexUnlock|Mutexunlock]]##
- ##[[KeyPgThreadCreate|Threadcreate]]##
- ##[[KeyPgThreadWait|Threadwait]]##
Deletions:
[[KeyPgDeclare declare]] [[KeyPgFunction function]] **Mutexcreate** ( ) [[KeyPgAs as]] [[KeyPgAny any]] [[KeyPgPtr ptr]]
The ##[[KeyPgAny any]] [[KeyPgPtr ptr]]## handle of the mutex created, or the null pointer (0) on failure.
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 ##[[KeyPgMutexLock Mutexlock]]## with that mutex (including the main thread executing main program), until it is unlocked with ##[[KeyPgMutexUnlock Mutexunlock]]##.
##Mutexcreate## creates a mutex, returning a handle which is to be referred to when locking, unlocking, or destroying the mutex. Mutexes created with ##Mutexcreate## should be destroyed when no longer needed or before the end of the program with ##[[KeyPgMutexDestroy Mutexdestroy]]##.
See also the ##[[KeyPgThreadCreate Threadcreate]]## examples.
Static As Integer I
MutexLock(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
Sleep 5
See also the similar ##[[KeyPgCondCreate Condcreate]]## example
- Threading is not allowed in the //[[CompilerOptlang -lang qb]]// dialect.
- ##[[KeyPgMutexDestroy Mutexdestroy]]##
- ##[[KeyPgMutexLock Mutexlock]]##
- ##[[KeyPgMutexUnlock Mutexunlock]]##
- ##[[KeyPgThreadCreate Threadcreate]]##
- ##[[KeyPgThreadWait Threadwait]]##


Revision [17648]

Edited on 2015-05-02 01:32:19 by FxMwikki [Update example]
Additions:
Locate 30, 62
Deletions:
Locate 30, 63


Revision [17646]

Edited on 2015-05-01 16:12:33 by FxMwikki [Update example]
Additions:
Static As Integer I
I += 1
Locate 30, 38
Print I;
Locate 30, 27
Print "calculated:";
Locate 30, 54
Print "plotted:";
Static As Integer I
I += 1
Locate 30, 63
Print I;
Sleep


Revision [17644]

Edited on 2015-05-01 04:28:30 by FxMwikki [Added link to the similar Condcreate example]
Additions:
See also the similar ##[[KeyPgCondCreate Condcreate]]## example


Revision [17642]

Edited on 2015-05-01 03:36:16 by FxMwikki [Correcting wording in example]
Additions:
'Principle of mutual exclusion
' Thread#A XOR Thread#B
'..... .....
'MutexLock(mut) MutexLock(mut)
' Do_something#A_with_exclusion Do_something#B_with_exclusion
'MutexUnlock(mut) MutexUnlock(mut)
'..... .....


Revision [17641]

Edited on 2015-04-30 15:22:49 by FxMwikki [Correcting wording in example]
Additions:
'Visual example of mutual exclusion between 2 threads by using Mutex:
Deletions:
'Visual example of threading synchronization using Mutex:


Revision [17640]

Edited on 2015-04-30 14:59:12 by FxMwikki [Correcting wording in example]
Additions:
'Behavior:
'- The first point must be pre-calculated.
'- Nothing prevents that a same calculated point could be plotted several times
'(depends on execution times of the loops between main thread and user thread).
'- Nothing prevents that a calculated point could be not plotted
'(same remark on the loop times).
Declare Static Sub Thread (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
Const true As Byte = Not false 'Constante "true"
Static Sub ThreadUDT.Thread (ByVal param As Any Ptr) 'Generic user thread procedure
Dim x As Integer
Sub PointOnCircle (ByVal p As Any Ptr)
Dim Pptr As Point2D Ptr = New Point2D
PointOnCircle(Pptr) ' Computation for a first point valid on the circle
PSet (Pptr->x, Pptr->y) 'Plotting one point
Deletions:
Declare Static Sub Thread (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
Const true As Byte = Not False 'Constante "true"
Static Sub ThreadUDT.Thread (Byval param As Any Ptr) 'Generic user thread procedure
Dim x AS Integer
Sub PointOnCircle (Byval p As Any Ptr)
Dim Pptr As Point2D ptr = New Point2D
Pptr->x = x0 + r0 * Cos(0)
pptr->y = y0 + r0 * Sin(0)
Pset (Pptr->x, Pptr->y)


Revision [17639]

Edited on 2015-04-29 15:52:03 by FxMwikki [Correcting wording in example]
Additions:
'there will be no longer mutual exclusion between computation of coordinates and plotting of points,
Deletions:
'the two threads ("user-defined" and "main") will not be in sync,


Revision [17439]

Edited on 2015-02-09 11:51:01 by FxMwikki [Only added an adjective and deleted a comma, but useful for understanding!]
Additions:
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 ##[[KeyPgMutexLock Mutexlock]]## with that mutex (including the main thread executing main program), until it is unlocked with ##[[KeyPgMutexUnlock Mutexunlock]]##.
Deletions:
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 variable used by a single thread, called multiple times), it should be "locked" during its use with a mutex. This halts all threads using ##[[KeyPgMutexLock Mutexlock]]## with that mutex (including the main thread executing main program), until it is unlocked with ##[[KeyPgMutexUnlock Mutexunlock]]##.


Revision [16963]

Edited on 2013-09-30 05:44:09 by FxMwikki [Added one example for mutex use]
Additions:
See also the ##[[KeyPgThreadCreate Threadcreate]]## examples.
{{fbdoc item="filename" value="examples/manual/threads/mutexcreate.bas"}}%%(freebasic)
'Visual example of threading synchronization using Mutex:
'the "user-defined thread" computes the points coordinates on a circle,
'and the "main thread" plots the points.
'
'If you comment out the lines containing "MutexLock" and "MutexUnlock"
'(inside "user-defined thread" or/and "main thread"),
'the two threads ("user-defined" and "main") will not be in sync,
'and many points will not be plotted on circle (due to non coherent coordinates).
'-----------------------------------------------------------------------------------------------------
Type ThreadUDT 'Generic user thread UDT
Dim handle As Any Ptr 'Any Ptr handle to user thread
Dim sync As Any Ptr 'Any Ptr handle to mutex
Dim quit As Byte 'Boolean to end user thread
Declare Static Sub Thread (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 by user thread
Const false As Byte = 0 'Constante "false"
Const true As Byte = Not False '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
MutexLock(tp->sync) 'Mutex (Lock) for user thread
tp->procedure(tp->p) 'Procedure(Any Ptr) to be executed by user thread
MutexUnlock(tp->sync) 'Mutex (Unlock) for user thread
Sleep 5
Loop Until tp->quit = tp->true 'Test for ending user thread
End Sub
'-----------------------------------------------------------------------------------------------------
Type Point2D
Dim x AS Integer
Dim y As Integer
End Type
Const x0 As Integer = 640 / 2
Const y0 As Integer = 480 / 2
Const r0 As Integer = 200
Const pi As Single = 4 * Atn(1)
Sub PointOnCircle (Byval 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 'To increase possibility of uncorrelated data occurrence
pp->y = y0 + r0 * Sin(teta)
End Sub
Screen 12
Locate 30, 2
Print "<any_key> : exit";
Dim Pptr As Point2D ptr = New Point2D
Pptr->x = x0 + r0 * Cos(0)
pptr->y = y0 + r0 * Sin(0)
Dim Tptr As ThreadUDT Ptr = New ThreadUDT
Tptr->sync = MutexCreate
Tptr->procedure = @PointOnCircle
Tptr->p = Pptr
Tptr->handle = ThreadCreate(@ThreadUDT.Thread, Tptr)
Do
MutexLock(Tptr->sync) 'Mutex (Lock) for main thread
Pset (Pptr->x, Pptr->y)
MutexUnlock(Tptr->sync) 'Mutex (Unlock) for main thread
Sleep 5
Loop Until Inkey <> ""

Tptr->quit = Tptr->true
ThreadWait(Tptr->handle)
MutexDestroy(Tptr->sync)
Delete Tptr
Delete Pptr
%%
Deletions:
See the ##[[KeyPgThreadCreate Threadcreate]]## examples.


Revision [16962]

Edited on 2013-09-27 14:06:07 by FxMwikki [Mutex can be used with all threads including the main thread executing main program]
Additions:
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 variable used by a single thread, called multiple times), it should be "locked" during its use with a mutex. This halts all threads using ##[[KeyPgMutexLock Mutexlock]]## with that mutex (including the main thread executing main program), until it is unlocked with ##[[KeyPgMutexUnlock Mutexunlock]]##.
Deletions:
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 variable used by a single thread, called multiple times), it should be "locked" during its use with a mutex. This halts all threads using ##[[KeyPgMutexLock Mutexlock]]## with that mutex, until it is unlocked with ##[[KeyPgMutexUnlock Mutexunlock]]##.


Revision [15299]

Edited on 2011-10-01 07:12:32 by DkLwikki [Point to KeyPgThreadCreate instead of duplicating]
Additions:
See the ##[[KeyPgThreadCreate Threadcreate]]## examples.
Deletions:
See the [[KeyPgThreadCreate Threadcreate]] examples.


Revision [15295]

Edited on 2011-10-01 07:09:34 by DkLwikki [Point to KeyPgThreadCreate instead of duplicating]
Additions:
- The DOS version of ""FreeBASIC"" does not allow for threads, as the OS does not support them.
- 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.
Deletions:
- The DOS version of FreeBASIC does not allow for threads, as the OS does not support them.
- 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.


Revision [15288]

Edited on 2011-10-01 07:06:13 by DkLwikki [Point to KeyPgThreadCreate instead of duplicating]
Additions:
See the [[KeyPgThreadCreate Threadcreate]] examples.
Deletions:
{{fbdoc item="filename" value="examples/manual/threads/threadsync1.bas"}}%%(freebasic)
'' Threading syncronyzation using Mutexes
'' If you comment out the lines containing "MutexLock" and "MutexUnlock",
'' the threads will not be in sync and some of the data may be printed
'' out of place.
Const MAX_THREADS = 10
Dim Shared As Any ptr ttylock
'' Teletype unfurls some text across the screen at a given location
Sub teletype( text As String, x As Integer, y As Integer )
''
'' This MutexLock makes simultaneously running threads wait for each
'' other, so only one at a time can continue and print output.
'' Otherwise, their Locates would interfere, since there is only one
'' cursor.
''
'' It's impossible to predict the order in which threads will arrive
'' here and which one will be the first to acquire the lock thus
'' causing the rest to wait.
''
MutexLock ttylock
For i As Integer = 0 To (Len(text) - 1)
Locate x, y + i
Print Chr(text[i])
Sleep 25
Next
'' MutexUnlock releases the lock and lets other threads acquire it.
MutexUnlock ttylock
End Sub
Sub thread( ByVal userdata As Any Ptr )
Dim As Integer id = CInt(userdata)
teletype "Thread (" & id & ").........", 1 + id, 1
End Sub
'' Create a mutex to syncronize the threads
ttylock = MutexCreate()
'' Create child threads
Dim As Any Ptr handles(0 To MAX_THREADS-1)
For i As Integer = 0 To MAX_THREADS-1
handles(i) = ThreadCreate(@thread, CPtr(Any Ptr, i))
If handles(i) = 0 Then
Print "Error creating thread:"; i
Exit For
End If
Next
'' This is the main thread. Now wait until all child threads have finished.
For i As Integer = 0 To MAX_THREADS-1
If handles(i) <> 0 Then
ThreadWait(handles(i))
End If
Next
'' Clean up when finished
MutexDestroy(ttylock)
%%
{{fbdoc item="filename" value="examples/manual/threads/threadsync2.bas"}}%%(freebasic)
'' Threaded consumer/producer example using mutexes
dim shared as any ptr produced, consumed
sub consumer( byval param as any ptr )
for i as integer = 0 to 9
mutexlock produced
print ", consumer gets:", i
sleep 500
mutexunlock consumed
next
end sub
sub producer( byval param as any ptr )
for i as integer = 0 to 9
print "Producer puts:", i;
sleep 500
mutexunlock produced
mutexlock consumed
next i
end sub
dim as any ptr consumer_id, producer_id
produced = mutexcreate
consumed = mutexcreate
if( ( produced = 0 ) or ( consumed = 0 ) ) then
print "Error creating mutexes! Exiting..."
end 1
end if
mutexlock produced
mutexlock consumed
consumer_id = threadcreate(@consumer)
producer_id = threadcreate(@producer)
if( ( producer_id = 0 ) or ( consumer_id = 0 ) ) then
print "Error creating threads! Exiting..."
end 1
end if
threadwait consumer_id
threadwait producer_id
mutexdestroy consumed
mutexdestroy produced
sleep
%%


Revision [15282]

Edited on 2011-10-01 01:47:18 by DkLwikki [Fix example, add second one]
Additions:
{{fbdoc item="filename" value="examples/manual/threads/threadsync1.bas"}}%%(freebasic)
Const MAX_THREADS = 10
Dim Shared As Any ptr ttylock
Sub teletype( text As String, x As Integer, y As Integer )
''
'' This MutexLock makes simultaneously running threads wait for each
'' other, so only one at a time can continue and print output.
'' Otherwise, their Locates would interfere, since there is only one
'' cursor.
''
'' It's impossible to predict the order in which threads will arrive
'' here and which one will be the first to acquire the lock thus
'' causing the rest to wait.
''
MutexLock ttylock
For i As Integer = 0 To (Len(text) - 1)
Locate x, y + i
Print Chr(text[i])
Sleep 25
Next
'' MutexUnlock releases the lock and lets other threads acquire it.
MutexUnlock ttylock
End Sub
Sub thread( ByVal userdata As Any Ptr )
Dim As Integer id = CInt(userdata)
teletype "Thread (" & id & ").........", 1 + id, 1
End Sub
'' Create a mutex to syncronize the threads
ttylock = MutexCreate()
'' Create child threads
Dim As Any Ptr handles(0 To MAX_THREADS-1)
For i As Integer = 0 To MAX_THREADS-1
handles(i) = ThreadCreate(@thread, CPtr(Any Ptr, i))
If handles(i) = 0 Then
Print "Error creating thread:"; i
Exit For
End If
Next
'' This is the main thread. Now wait until all child threads have finished.
For i As Integer = 0 To MAX_THREADS-1
If handles(i) <> 0 Then
ThreadWait(handles(i))
End If
Next
'' Clean up when finished
MutexDestroy(ttylock)
{{fbdoc item="filename" value="examples/manual/threads/threadsync2.bas"}}%%(freebasic)
'' Threaded consumer/producer example using mutexes
dim shared as any ptr produced, consumed
sub consumer( byval param as any ptr )
for i as integer = 0 to 9
mutexlock produced
print ", consumer gets:", i
sleep 500
mutexunlock consumed
next
end sub
sub producer( byval param as any ptr )
for i as integer = 0 to 9
print "Producer puts:", i;
sleep 500
mutexunlock produced
mutexlock consumed
next i
end sub
dim as any ptr consumer_id, producer_id
produced = mutexcreate
consumed = mutexcreate
if( ( produced = 0 ) or ( consumed = 0 ) ) then
print "Error creating mutexes! Exiting..."
end 1
mutexlock produced
mutexlock consumed
consumer_id = threadcreate(@consumer)
producer_id = threadcreate(@producer)
if( ( producer_id = 0 ) or ( consumer_id = 0 ) ) then
print "Error creating threads! Exiting..."
end 1
threadwait consumer_id
threadwait producer_id
mutexdestroy consumed
mutexdestroy produced
sleep
Deletions:
{{fbdoc item="filename" value="examples/manual/threads/mutexcreate.bas"}}%%(freebasic)
const MAX_THREADS = 10
DECLARE SUB thread( byval id_ptr as any ptr )
DECLARE SUB teletype (BYVAL text AS STRING, BYVAL x AS INTEGER, BYVAL y AS INTEGER)
DIM SHARED threadsync AS any ptr
dim i as integer
DIM handleTb(0 to MAX_THREADS-1) AS any ptr
'' Create a mutex to syncronize the threads
threadsync = MUTEXCREATE
'' Create threads
for i = 0 to MAX_THREADS-1
handleTb(i) = THREADCREATE(@thread, @i)
IF handleTb(i) = 0 THEN
PRINT "Error creating thread:"; i
exit for
END IF
next
'' Wait until all threads are finished
for i = 0 to MAX_THREADS-1
if( handleTb(i) <> 0 ) then
THREADWAIT( handleTb(i) )
next
teletype "Testing.................", 1, 1
teletype "Testing again...........", 10, 1
'' Discard the mutex when we are through using teletype
MUTEXDESTROY threadsync
SUB thread( byval id_ptr as any ptr )
dim id as integer
id = *cast( integer ptr, id_ptr )
teletype "Thread (" & id & ").........", 1, 1+id
END SUB
SUB teletype (BYVAL text AS STRING, BYVAL x AS INTEGER, BYVAL y AS INTEGER)
DIM i AS INTEGER
FOR i = 0 TO LEN(text)-1
'' MutexLock prevents the two simultaneously running
'' threads from sharing "x", "y", and "a"
MUTEXLOCK threadsync
LOCATE y, x+i
PRINT CHR(text[i])
'' MutexUnlock releases these variables for other use
MUTEXUNLOCK threadsync
SLEEP 25
NEXT
END SUB


Revision [14369]

Edited on 2009-08-29 21:54:50 by CountingPine [Remove CamelCase links in "New to FreeBASIC"]
Additions:
- New to ""FreeBASIC""
Deletions:
- New to FreeBASIC


Revision [12357]

The oldest known version of this page was created on 2008-01-18 14:17:27 by JeffMarshall [Remove CamelCase links in "New to FreeBASIC"]
Valid XHTML :: Valid CSS: :: Powered by WikkaWiki



sf.net phatcode