Szymański's algorithm: Difference between revisions

Added FreeBasic
(Added FreeBasic)
Line 22:
https://en.wikipedia.org/wiki/Szyma%C5%84ski%27s_algorithm
"""
 
=={{header|FreeBASIC}}==
<syntaxhighlight lang="vb">Const MAX_THREADS = 6
 
Dim Shared As Any Ptr ttylock
Dim Shared As Integer criticalValue = 1
 
Sub thread( Byval userdata As Any Ptr )
''
'' 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
Dim As Integer id = Cint(userdata)
criticalvalue += id * 3
criticalvalue \= 2
Sleep 25, 1
Print Using "Thread # changed the critical value to ##."; id; criticalvalue
'' MutexUnlock releases the lock and lets other threads acquire it.
Mutexunlock ttylock
End Sub
 
'' Create a mutex to syncronize the threads
ttylock = Mutexcreate()
 
'' Create child threads
Dim As Any Ptr handles(1 To MAX_THREADS)
For i As Integer = 1 To MAX_THREADS
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 = 1 To MAX_THREADS
If handles(i) <> 0 Then
Threadwait(handles(i))
End If
Next
 
'' Clean up when finished
Mutexdestroy(ttylock)
 
Sleep</syntaxhighlight>
{{out}}
<pre>Thread 1 changed the critical value to 2.
Thread 4 changed the critical value to 7.
Thread 3 changed the critical value to 8.
Thread 2 changed the critical value to 7.
Thread 5 changed the critical value to 11.
Thread 6 changed the critical value to 14.</pre>
 
=={{header|Julia}}==
2,169

edits