ThreadWait
Waits until the designated thread has been completed before returning
Syntax
`
Declare Sub ThreadWait ( ByVal id As Any Ptr )
`
Usage
`
ThreadWait( id )
`
Parameters
`id`
`Any Ptr` handle of a thread created by `ThreadCreate`
Description
`Threadwait` doesn't return until the thread designated by `id` ends. `Threadwait` does not force the thread to end; if a thread requires a signal to force its end, a mechanism such as shared variables must be used.
Threads are launched by the `ThreadCreate` function.
To avoid simultaneous access to shared resources from different threads, FreeBASIC implements mutexes, mutual exclusion locks that can be "owned" by a single thread when doing critical work. See `MutexCreate`, `MutexLock`, `MutexUnlock`, `MutexDestroy`
Example
`
Dim Shared printsync As Any Ptr
Sub mythread(ByVal idp As Any Ptr)
Var id = CInt(idp)
Dim As Double t, w
Dim As Integer i, n
If( id = 1 ) Then
w = 1
n = 10
Else
w = 0.3
n = 5
End If
For i = 1 To n
MutexLock printsync
Print "Thread #"; id; ": on step #"; i
MutexUnlock printsync
'' simulate some work
t = Timer
While( Timer - t ) < w
Wend
Next i
MutexLock printsync
Print "Thread #"; id; " is done "
MutexUnlock printsync
End Sub
Dim As Any Ptr t1, t2
Print "Starting threads ... "
'' create a mutex to sync printing
printsync = MutexCreate()
'' create 2 threads, each taking a different
'' amount of time to complete
t1 = ThreadCreate( @mythread, Cast(Any Ptr, 1) )
t2 = ThreadCreate( @mythread, Cast(Any Ptr, 2) )
'' wait for threads to complete
ThreadWait( t1 )
ThreadWait( t2 )
MutexDestroy printsync
Print "All done."
`
Dialect Differences

- Threading is not allowed in `-lang qb`

Platform Differences

- Threadwait is not available with the DOS version / target of FreeBASIC, because multithreading is not supported by DOS kernel nor the used extender.
- 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

- `ThreadCreate`
- `MutexCreate`
- `MutexLock`
- `MutexUnlock`
- `MutexDestroy`