BRL.Threads: Types Functions Source  


Welcome to the weird and wonderful world of multithreading!

Multithreading effectively allows your programs to do several things at the same time. The word 'thread' in this context means 'thread of execution' - or, the series of instructions, branches and so on executed by your program. Most programs are 'single threaded', meaning there is only one thread of execution. However, more and more programs are using multiple threads.

Multithreading used to be achieved by software trickery, which made threading useful but not really faster - there was still only one CPU pretending to do multiple things at the same time! But these days, multicore CPUs mean that threading can be used to truly do multiple things at the same time (or 'in parallel').

Creating a thread is easy - just call CreateThread. You will need to provide a function for the thread to use as it's 'entry point'. Once the thread is created, this function will start executing in parallel with the code that called CreateThread. When the thread function returns, that thread will be 'terminated'.

Alas, threading turns out to be rather tricky due to an issue known as 'synchronization'. Synchronization is required when you need to prevent multiple threads from modifying or accessing the same data at the same time. Synchronization usually involves a thread 'blocking'. When a thread blocks, it completely halts execution until another thread does something that causes it to 'unblock' and resume execution.

BlitzMax provides 2 primitives known as 'mutexes' and 'semaphores' to assist with synchronization:

* Mutexes provide a simple locking mechanism. Only one thread at a time can lock a mutex (using LockMutex or TryLockMutex), so this is an easy way to protect resources from simultaneous access. If a thread calls LockMutex and the mutex is already locked by another thread, the current thread will block until the other thread releases the mutex using UnlockMutex. So don't forget to UnlockMutex a mutex after you are finished with it!

* Semaphores provide a synchronized counting mechanism, and contain an internal integer counter. There are 2 operations you can perform on a semaphore - post and wait. Posting a semaphore (using PostSemaphore) causes the semaphore's internal counter to be incremented, while waiting for a semaphore (using WaitSemaphore) will cause the current thread to block until the semaphore's internal counter is greater than 0. When it is, the counter is decremented and the thread unblocks. Semaphores are very useful for producer/consumer type situations.

Types

TThreadThread type
TThreadDataThreadData type
TMutexMutex type
TSemaphoreSemaphore type
TCondVarCondVar type

Functions

CreateThreadCreate a thread
MainThreadGet main thread
CurrentThreadGet current thread
DetachThreadDetach a thread
WaitThreadWait for a thread to finish
ThreadRunningCheck if a thread is running
CreateThreadDataCreate thread data
SetThreadDataValueSet thread data value
GetThreadDataValueGet thread data value
CreateMutexCreate a mutex
CloseMutexClose a mutex
LockMutexLock a mutex
TryLockMutexTry to lock a mutex
UnlockMutexUnlock a mutex
CreateSemaphoreCreate a semaphore
CloseSemaphoreClose a semaphore
WaitSemaphoreWait for a semaphore
PostSemaphorePost a semaphore
CreateCondVarCreate a condvar
CloseCondVarClose a condvar
WaitCondVarWait for a condvar
SignalCondVarSignal a condvar
BroadcastCondVarBroadcast a condvar
CompareAndSwapCompare and swap
AtomicAddAtomic add
AtomicSwapAtomically swap values

Function reference

Function CreateThread:TThread( entry:Object( data:Object ),data:Object )
ReturnsA new thread object.
DescriptionCreate a thread
Information Creates a thread and returns a thread object.

The value returned by the thread entry routine can be later retrieved using WaitThread.

To 'close' a thread, call either DetachThread or WaitThread. This isn't strictly necessary as the thread will eventually be closed when it is garbage collected, however, it may be a good idea if you are creating many threads very often, as some operating systems have a limit on the number of threads that can be allocated at once.

Example
'Make sure to have 'Threaded build' enabled!
'
Strict

'Custom print that shows which thread is doing the printing
Function MyPrint( t$ )
	If CurrentThread()=MainThread() 
		Print "Main thread: "+t
	Else
		Print "Child thread: "+t
	EndIf
End Function

'Our thread function
Function MyThread:Object( data:Object )

	'show data we were passed
	Myprint data.ToString()

	'do some work
	For Local i=1 To 1000
		MyPrint "i="+i
	Next
	
	'return a value from the thread
	Return "Data returned from child thread."
	
End Function

MyPrint "About to start child thread."

'create a thread!
Local thread:TThread=CreateThread( MyThread,"Data passed to child thread." )

'wait for thread to finish and print value returned from thread
MyPrint WaitThread( Thread ).ToString()

Function MainThread:TThread()
ReturnsA thread object representing the main application thread.
DescriptionGet main thread

Function CurrentThread:TThread()
ReturnsA thread object representing the current thread.
DescriptionGet current thread

Function DetachThread( thread:TThread )
DescriptionDetach a thread
Information DetachThread closes a thread's handle, but does not halt or otherwise affect the target thread.

Once one a thread has been detached, it wil no longer be possible to use WaitThread to get its return value.

This allows the thread to run without your program having to continually check whether it has completedin order to close it.

Function WaitThread:Object( thread:TThread )
ReturnsThe object returned by the thread entry routine.
DescriptionWait for a thread to finish
Information WaitThread causes the calling thread to block until the target thread has completed execution.

If the target thread has already completed execution, WaitThread returns immediately.

The returned object is the object returned by the thread's entry routine, as passed to CreateThread.

Function ThreadRunning( thread:TThread )
ReturnsTrue if thread is still running, otherwise False.
DescriptionCheck if a thread is running

Function CreateThreadData:TThreadData()
ReturnsA new thread data object.
DescriptionCreate thread data

Function SetThreadDataValue( data:TThreadData,value:Object )
DescriptionSet thread data value

Function GetThreadDataValue:Object( data:TThreadData )
DescriptionGet thread data value

Function CreateMutex:TMutex()
ReturnsA new mutex object
DescriptionCreate a mutex
Example
'Make sure to have 'Threaded build' enabled!
'
Strict

'a global list that multiple threads want to modify
Global list:TList=New TList

'a mutex controlling access to the global list
Global listMutex:TMutex=CreateMutex()

Function MyThread:Object( data:Object )

	For Local item=1 To 10
		'simulate 'other' processing...
		Delay Rand( 10,50 )

		'lock mutex so we can safely modify global list
		LockMutex listMutex

		'modify list
		list.AddLast "Thread "+data.ToString()+" added item "+item

		'unlock mutex
		UnlockMutex listMutex
	Next
	
End Function

Local threads:TThread[10]

'Create worker threads
For Local i=0 Until 10
	threads[i]=CreateThread( MyThread,String( i+1 ) )
Next

Print "Waiting for worker threads..."

'Wait for worker threads to finish
For Local i=0 Until 10
	WaitThread threads[i]
Next

'Show the resulting list
'
'Note: We don't really have to lock the mutex here, as there are no other threads running.
'Still, it's a good habit to get into.
LockMutex listMutex
For Local t$=EachIn list
	Print t
Next
UnlockMutex listMutex

Function CloseMutex( mutex:TMutex )
DescriptionClose a mutex

Function LockMutex( mutex:TMutex )
DescriptionLock a mutex

Function TryLockMutex( mutex:TMutex )
ReturnsTrue if mutex was successfully locked; False if mutex was already locked by another thread.
DescriptionTry to lock a mutex

Function UnlockMutex( mutex:TMutex )
DescriptionUnlock a mutex

Function CreateSemaphore:TSemaphore( count )
ReturnsA new semaphore object
DescriptionCreate a semaphore
Example
'Make sure to have 'Threaded build' enabled!
'
Strict

'a simple queue
Global queue$[100],put,get

'a counter semaphore
Global counter:TSemaphore=CreateSemaphore( 0 )

Function MyThread:Object( data:Object )

	'process 100 items
	For Local item=1 To 100
	
		'add an item to the queue
		queue[put]="Item "+item
		put:+1
		
		'increment semaphore count.
		PostSemaphore counter
	
	Next
		
End Function

'create worker thread
Local thread:TThread=CreateThread( MyThread,Null )

'receive 100 items
For Local i=1 To 100

	'Wait for semaphore count to be non-0, then decrement.
	WaitSemaphore counter
	
	'Get an item from the queue
	Local item$=queue[get]
	get:+1
	
	Print item

Next

Function CloseSemaphore( semaphore:TSemaphore )
DescriptionClose a semaphore

Function WaitSemaphore( semaphore:TSemaphore )
DescriptionWait for a semaphore

Function PostSemaphore( semaphore:TSemaphore )
DescriptionPost a semaphore

Function CreateCondVar:TCondVar()
ReturnsA new condvar object
DescriptionCreate a condvar

Function CloseCondVar( condvar:TCondVar )
DescriptionClose a condvar

Function WaitCondVar( condvar:TCondVar,mutex:TMutex )
DescriptionWait for a condvar

Function SignalCondVar( condvar:TCondVar )
DescriptionSignal a condvar

Function BroadcastCondVar( condvar:TCondVar )
DescriptionBroadcast a condvar

Function CompareAndSwap( target Var,oldValue,newValue )
ReturnsTrue if target was updated
DescriptionCompare and swap
Information Atomically replace target with new_value if target equals old_value.

Function AtomicAdd( target Var,value )
ReturnsPreviuous value of target
DescriptionAtomic add
Information Atomically add value to target.

Function AtomicSwap( target Var,value )
ReturnsThe old value of target
DescriptionAtomically swap values