BlitzMax

BlitzMax

  • Downloads
  • Docs
  • API
  • Resources
  • About

›Threads

BlitzMax API

  • Introduction

BRL

    Audio

    • Introduction
    • TChannel
    • TSound

    AudioSample

    • Introduction
    • TAudioSample
    • TAudioSampleLoader

    Bank

    • Introduction
    • TBank

    BankStream

    • Introduction
    • TBankStream

    Base64

    • Introduction
    • TBase64

    Blitz

    • Introduction
    • TArrayBoundsException
    • TBlitzException
    • TNullFunctionException
    • TNullMethodException
    • TNullObjectException
    • TOutOfDataException
    • TRuntimeException
  • BRL.BMPLoader
  • Clipboard

    • Introduction
    • TClipboard
    • TClipboardOpts
    • TWin32ClipboardOpts
    • TX11ClipboardOpts
  • BRL.D3D7Max2D
  • BRL.D3D9Max2D
  • BRL.DirectSoundAudio
  • BRL.EndianStream
  • Event

    • Introduction
    • TEvent
  • BRL.EventQueue
  • BRL.FileSystem
  • BRL.FreeAudioAudio
  • BRL.GLGraphics
  • BRL.GLMax2D
  • BRL.GNet
  • BRL.Graphics
  • BRL.Hook
  • IO

    • Introduction
    • MaxIO
  • BRL.JPGLoader
  • BRL.KeyCodes
  • LinkedList

    • Introduction
    • TList
    • TListEnum
    • TLink

    Map

    • Introduction
    • TMap
    • TIntMap
    • TIntKey
    • TPtrMap
    • TPtrKey
    • TStringMap
  • BRL.Math
  • Matrix

    • Introduction
    • SMat2D
    • SMat2F
    • SMat2I
    • SMat3D
    • SMat3F
    • SMat3I
    • SMat4D
    • SMat4F
    • SMat4I

    Max2D

    • Introduction
    • TImage

    MaxLua

    • Introduction
    • TLuaClass
    • TLuaObject
  • BRL.OGGLoader
  • BRL.OpenALAudio
  • ObjectList

    • Introduction
    • TObjectList
    • TObjectListEnumerator
    • TObjectListReverseEnumerator

    Pixmap

    • Introduction
    • TPixmap
    • TPixmapLoader
  • BRL.PNGLoader
  • BRL.PolledInput
  • Quaternion

    • Introduction
    • SQuatD
    • SQuatF
    • SQuatI
  • BRL.RamStream
  • Random

    • Introduction
    • TRandom

    Reflection

    • Introduction
    • TTypeId
    • TMember
    • TConstant
    • TField
    • TGlobal
    • TFunction
    • TMethod
  • BRL.Retro
  • BRL.Socket
  • BRL.SocketStream
  • BRL.StandardIO
  • Stream

    • Introduction
    • TCStream
    • TIO
    • TStream
    • TStreamException
    • TStreamFactory
    • TStreamReadException
    • TStreamWrapper
    • TStreamWriteException

    StringBuilder

    • Introduction
    • TStringBuilder
    • TSplitBuffer
  • BRL.System
  • BRL.SystemDefault
  • BRL.TextStream
  • BRL.TGALoader
  • ThreadPool

    • Introduction
    • TRunnable
    • TThreadPoolExecutor

    Threads

    • Introduction
    • TThread
    • TThreadData
    • TMutex
    • TSemaphore
    • TCondVar

    Timer

    • Introduction
    • TChrono
  • BRL.TimerDefault
  • Vector

    • Introduction
    • SVec2D
    • SVec2F
    • SVec2I
    • SVec3D
    • SVec3F
    • SVec3I
    • SVec4D
    • SVec4F
    • SVec4I

    Volumes

    • Introduction
    • TVolume
  • BRL.WAVLoader

Text

    CSV

    • Introduction
    • TCsvParser
    • TCsvHeader
    • TCsvRow
    • TCsvOptions
    • SCsvColumn

    Format

    • Introduction
    • TFormatter

    Ini

    • Introduction
    • TIni
    • TIniProperty
    • TIniSection

    JConv

    • Introduction
    • TJConv
    • TJConvBuilder
    • TJConvSerializer

    Json

    • Introduction
    • TJSON
    • TJSONObject
    • TJSONString
    • TJSONInteger
    • TJSONReal
    • TJSONBool
    • TJSONArray
    • TJSONNull
    • TJSONError
    • TJSONNumber

    Regex

    • Introduction
    • TRegEx
    • TRegExMatch
    • TRegExOptions
    • TRegExException

    TOML

    • Introduction
    • ETomlNodeType
    • TToml
    • ITomlNode
    • STomlDate
    • STomlDateTime
    • STomlTime
    • TTomlArray
    • TTomlInteger
    • TTomlString
    • TTomlTable
    • TTomlBoolean

    Xml

    • Introduction
    • TxmlDoc
    • TxmlNode
    • TxmlAttribute

MaxGUI

  • MaxGUI.MaxGUI
  • MaxGUI.Drivers
  • MaxGUI.Localization
  • MaxGUI.ProxyGadgets
  • MaxGUI.CocoaMaxGUI
  • MaxGUI.Win32MaxGUIEx

PUB

  • Pub.FreeJoy
  • Pub.FreeProcess
  • Pub.Glad
  • Pub.Glew
  • Joystick

    • Introduction
    • TJoystickDriver
  • Pub.Lua
  • Pub.OpenAL
  • Pub.OpenGLES
  • Pub.xmmintrin
  • Pub.ZLib

Crypto

    Digest

    • Introduction
    • TMessageDigest
    • TDigestRegister
    • TNoSuchAlgorithmException

    Cipher

    • Introduction
    • TCipher
    • TCipherMode
    • Crypto.AESCipher
    • Crypto.AnubisCipher
    • Crypto.BlowfishCipher
    • Crypto.CamelliaCipher
    • Crypto.Cast5Cipher
    • Crypto.DESCipher
    • Crypto.IdeaCipher
    • Crypto.KasumiCipher
    • Crypto.KhazadCipher
    • Crypto.KSeedCipher
    • Crypto.NoekeonCipher
    • Crypto.SerpentCipher
    • Crypto.SkipjackCipher
    • Crypto.TwofishCipher
    • Crypto.XTeaCipher

    CBCMode

    • Introduction
    • TCBCCipherMode

    CFBMode

    • Introduction
    • TCFBCipherMode

    CTRMode

    • Introduction
    • TCTRCipherMode

    ECBMode

    • Introduction
    • TECBCipherMode

    F8Mode

    • Introduction
    • TF8CipherMode

    LRWMode

    • Introduction
    • TLRWCipherMode

    OFBMode

    • Introduction
    • TOFBCipherMode

    XTSMode

    • Introduction
    • TXTSCipherMode

    Blake2BDigest

    • Introduction
    • TBlake2B_512
    • TBlake2B_384
    • TBlake2B_256
    • TBlake2B_160

    CRC32

    • Introduction
    • TCRC32

    MD5Digest

    • Introduction
    • TMD5

    Ripemd320Digest

    • Introduction
    • TRipemd320

    Ripemd356Digest

    • Introduction
    • TRipemd256

    Ripemd160Digest

    • Introduction
    • TRipemd160

    Ripemd128Digest

    • Introduction
    • TRipemd128

    SHA1Digest

    • Introduction
    • TSHA1

    SHA256Digest

    • Introduction
    • TSHA256

    SHA512Digest

    • Introduction
    • TSHA512

    SHA3Digest

    • Introduction
    • TSHA3_512
    • TSHA3_384
    • TSHA3_256
    • TSHA3_224

    TigerDigest

    • Introduction
    • TTiger

    WhirlpoolDigest

    • Introduction
    • TWhirlpool

    Crypto

    • Introduction
    • TCryptoRandom
    • TCryptoSecretBox
    • TCryptoHash
    • TCryptoSign
    • TCryptoKeyExchange
    • TCryptoKey
    • TCryptoHashKey
    • TCryptoSecretBoxKey
    • TCryptoSignature
    • TCryptoExchangeKeyPair
    • TCryptoSessionKeyPair
    • TCryptoNPacket
    • TCryptoKK1Packet
    • TCryptoKK2Packet
    • TCryptoXX1Packet
    • TCryptoXX2Packet
    • TCryptoXX3Packet
    • TCryptoExchangeState
    • TCryptoPWHashMasterKey
    • TCryptoPWHashStoredKey
    • TCryptoPasswordHash

SDL

    SDL

    • Introduction
    • TSDLStream

    SDLSystem

    • Introduction
    • TSDLMultiGesture

    SDLVideo

    • Introduction
    • TSDLDisplay
    • TSDLDisplayMode
    • TSDLGLContext
    • TSDLWindow

    SDLRender

    • Introduction
    • TSDLRenderer
    • TSDLTexture

    SDLTimer

    • Introduction
    • TSDLTimer

    SDLHaptic

    • Introduction
    • TSDLHaptic
    • TSDLHapticCondition
    • TSDLHapticConstant
    • TSDLHapticCustom
    • TSDLHapticDirection
    • TSDLHapticEffect
    • TSDLHapticLeftRight
    • TSDLHapticPeriodic
    • TSDLHapticRamp

    SDLSensor

    • Introduction
    • TSDLSensor
  • SDL.SDLFreeAudio
  • SDL.GLSDLMax2D
  • SDL.GL2SDLMax2D
  • SDL.D3D9SDLMax2D
  • SDLVirtualJoystick

    • Introduction
    • TVirtualJoystick

Steam

    SteamSDK

    • Introduction
    • TSteamClient
    • TSteamUtils
    • TSteamUserStats
    • TSteamFriends
    • TSteamUGC
    • ISteamFriendsListener
    • ISteamUGCListener
    • ISteamUserStatsListener
    • ISteamUtilsListener
    • EItemPreviewType
    • EPersonaChange
    • EPersonaState
    • ERemoteStoragePublishedFileVisibility
    • EUGCMatchingUGCType
    • EUGCQuery
    • EUserRestriction
    • EUserUGCList
    • EWorkshopFileType
Edit

BRL.Threads

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

TypeDescription
TThreadThread type
TThreadDataThreadData type
TMutexMutex type
TSemaphoreSemaphore type
TCondVarCondVar type

Functions

Function CreateThread:TThread( entry:Object( data:Object ),data:Object )

Create a thread

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.

Returns

A new thread object.

Example

SuperStrict

'Custom print that shows which thread is doing the printing
Function MyPrint( t:String )
    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:Int = 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()

Get main thread

Returns

A thread object representing the main application thread.


Function CurrentThread:TThread()

Get current thread

Returns

A thread object representing the current thread.


Function DetachThread( thread:TThread )

Detach a thread

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 )

Wait for a thread to finish

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.

Returns

The object returned by the thread entry routine.


Function ThreadRunning:Int( thread:TThread )

Check if a thread is running

Returns

True if thread is still running, otherwise False.


Function CreateThreadData:TThreadData()

Create thread data

Returns

A new thread data object.


Function SetThreadDataValue( data:TThreadData,value:Object )

Set thread data value


Function GetThreadDataValue:Object( data:TThreadData )

Get thread data value


Function CreateMutex:TMutex()

Create a mutex

Returns

A new mutex object

Example

'Make sure to have 'Threaded build' enabled!
'
SuperStrict

'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:Int = 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:Int = 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:Int = 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:String = EachIn list
    Print t
Next
UnlockMutex listMutex


Function CloseMutex( mutex:TMutex )

Close a mutex


Function LockMutex( mutex:TMutex )

Lock a mutex


Function TryLockMutex:Int( mutex:TMutex )

Try to lock a mutex

Returns

True if mutex was successfully locked; False if mutex was already locked by another thread.


Function UnlockMutex( mutex:TMutex )

Unlock a mutex


Function CreateSemaphore:TSemaphore( count:Int )

Create a semaphore

Returns

A new semaphore object

Example

'Make sure to have 'Threaded build' enabled!
'
SuperStrict

' a simple queue
Global queue:String[100],put:Int,get:Int

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

Function MyThread:Object( data:Object )

    ' process 100 items
    For Local item:Int = 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:Int = 1 To 100

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

Next


Function CloseSemaphore( semaphore:TSemaphore )

Close a semaphore


Function WaitSemaphore( semaphore:TSemaphore )

Wait for a semaphore


Function PostSemaphore( semaphore:TSemaphore )

Post a semaphore


Function CreateCondVar:TCondVar()

Create a condvar

Returns

A new condvar object


Function CloseCondVar( condvar:TCondVar )

Close a condvar


Function WaitCondVar( condvar:TCondVar,mutex:TMutex )

Wait for a condvar


Function SignalCondVar( condvar:TCondVar )

Signal a condvar


Function BroadcastCondVar( condvar:TCondVar )

Broadcast a condvar


Function CompareAndSwap:Int( target:Int Var,oldValue:Int,newValue:Int )

Compare and swap

Atomically replace target with new_value if target equals old_value.

Returns

True if target was updated


Function AtomicAdd:Int( target:Int Var,value:Int )

Atomic add

Atomically add value to target.

Returns

Previuous value of target


Function AtomicSwap:Int( target:Int Var,value:Int )

Atomically swap values

Returns

The old value of target


← TThreadPoolExecutorTThread →
  • Types
  • Functions
    • Function CreateThread:TThread( entry:Object( data:Object ),data:Object )
    • Function MainThread:TThread()
    • Function CurrentThread:TThread()
    • Function DetachThread( thread:TThread )
    • Function WaitThread:Object( thread:TThread )
    • Function ThreadRunning:Int( thread:TThread )
    • Function CreateThreadData:TThreadData()
    • Function SetThreadDataValue( data:TThreadData,value:Object )
    • Function GetThreadDataValue:Object( data:TThreadData )
    • Function CreateMutex:TMutex()
    • Function CloseMutex( mutex:TMutex )
    • Function LockMutex( mutex:TMutex )
    • Function TryLockMutex:Int( mutex:TMutex )
    • Function UnlockMutex( mutex:TMutex )
    • Function CreateSemaphore:TSemaphore( count:Int )
    • Function CloseSemaphore( semaphore:TSemaphore )
    • Function WaitSemaphore( semaphore:TSemaphore )
    • Function PostSemaphore( semaphore:TSemaphore )
    • Function CreateCondVar:TCondVar()
    • Function CloseCondVar( condvar:TCondVar )
    • Function WaitCondVar( condvar:TCondVar,mutex:TMutex )
    • Function SignalCondVar( condvar:TCondVar )
    • Function BroadcastCondVar( condvar:TCondVar )
    • Function CompareAndSwap:Int( target:Int Var,oldValue:Int,newValue:Int )
    • Function AtomicAdd:Int( target:Int Var,value:Int )
    • Function AtomicSwap:Int( target:Int Var,value:Int )
BlitzMax
Docs
Getting StartedDownloadsAbout
Community
ResourcesSyntaxBomb Forums
More
GitHubStarChat on Discord
Copyright © 2023 Bruce A Henderson