PureBasic - Thread

Overview

A thread is a part of a program which runs asynchronously, in the background of this program. This means it's possible to perform long operations (compression, image processing, etc) without halting the whole program and let the user continue to do other things. A thread runs within your program, it's not another process. When the main program exits, all the threads are destroyed. Under PureBasic, threads are simply a procedure which is called asynchronously. The thread runs until the procedure exits.

Examples of places of programs where threads are useful are when you need to be able to handle multiple situations with different response times or which occur at different intervals. In the above paragraph, the response times of image processing and the user interface are quite different (you would want to wait for the image to be processed but always have the user interface to respond).

PureBasic has a special compiler setting to create thread-safe executables. (/THREAD command-line switch or "create thread-safe executable" in the IDE compiler options). Without this mode, certain functions (and also the string access) are faster, but not safe to use in threads. It is still possible to create threads without this mode but it is not recommended, as even something simple like a local string access can be dangerous and needs to be protected. Enabling this option makes these things save inside threads, but comes at the price of some speed. The decision on whether or not to use threads should therefore done with care, and the threadmode should only be used when there is a real need for it.

Note: Threads need to be used carefully because it is possible that you can have multiple access to shared resources (memory, variables, files, etc) and you need to manually ensure that you do run into trouble because of this. The Mutex functions in this library can be used to synchronize access to such shared resources.

Using the Threaded keyword it's possible to create thread-based persistent objects (variables, arrays, lists, maps).

Note: Don't use DirectX inside threads (MS Windows limitation)! If you need to display graphics in threads use Images and 2DDrawing instead.

Command Index

CreateMutex
CreateSemaphore
CreateThread
FreeMutex
FreeSemaphore
IsThread
KillThread
LockMutex
PauseThread
ResumeThread
SignalSemaphore
ThreadID
ThreadPriority
TryLockMutex
TrySemaphore
UnlockMutex
WaitSemaphore
WaitThread

Example

Thread.pb

Supported OS

All

Reference Manual - Index