Unit Threads

From Ultibo.org
Revision as of 04:18, 21 April 2017 by Ultibo (Talk | contribs)

Jump to: navigation, search

Return to Unit Reference


Description


Ultibo Threads interface unit

Locking Primitives

Spin -

A simple spin lock for fast mutually exclusive access to data. Threads "spin" while waiting to acquire the lock and do not yield the CPU unless pre-empted.

Non recursive (can only be acquired once by the same thread)

Includes IRQ/FIQ entry and exit routines to Save/Restore the IRQ/FIQ state.

Suitable for use by Interrupt handlers if non interrupt callers use the IRQ/FIQ entry and exit routines to Lock and Unlock.

Suitable for use on multiprocessor systems if the lock is allocated from shared memory (Determined during initialization).

Not recommended for long held operations or holding during I/O operations.

Access is not serialized, the next thread to try obtaining the lock when it is released will succeed even if that thread was not the first waiting.

Usage:

Create/Destroy

Spin locks are created using SpinCreate() and destroyed using SpinDestroy(), these functions should not be called from within an Interrupt handler. Lock/Unlock (Data accessed only by threads)

To synchronize data access between threads each thread should call SpinLock() before accessing the data and SpinUnlock() when finished accessing the data. These calls do not affect the state of IRQs or FIQs and therefore do not impact interrupt latency. Lock/Unlock (Data accessed by threads and interrupt handlers)

To use a Spin lock to synchronise data access between threads and an interrupt handler each thread should call SpinLockIRQ() or SpinLockFIQ(), depending on whether the interrupt handler is servicing IRQ or FIQ requests, before accessing the data and SpinUnlockIRQ() or SpinUnlockFIQ() when finished accessing the data. These calls disable interrupts before acquiring the lock (with deadlock protection) and restore interrupts after releaseing the lock and therefore should only be used to protect very short sections of code accessing shared data to minimize the impact on interrupt latency.

Interrupt handlers should call SpinLock() before accessing the data and SpinUnlock() when finished accessing the data. In a Uniprocessor system it is technically not necessary for interrupt handlers to call lock/unlock as the use of IRQ/FIQ disable/enable will prevent interrupt handlers from executing while a thread has the lock. On a Multiprocessor system however interrupt handlers can execute on one processor while a thread is executing on another (which will not deadlock), to correctly synchronize data access both threads and interrupt handlers should call the appropriate lock/unlock before and after access to the data.

Lock Hierachy -

It is safe to acquire one lock using SpinLock() then another lock using SpinLock() and then release them in reverse order.

It is also safe to acquire one lock using SpinLock() then another lock using SpinLockIRQ(or FIQ)() and then release them in reverse order.

It is NOT safe to acquire one lock using SpinLockIRQ(or FIQ)() then another lock using SpinLock() and then release them in reverse order. This is because the first SpinLockIRQ(or FIQ)() can disable the scheduling and prevent thread preemption. If another thread is already holding the second lock then this sequence will deadlock (except on a multicore system where the other thread is running on a different CPU).

It is also safe to acquire one lock using SpinLockIRQ(or FIQ)() then another lock using SpinLockIRQ(or FIQ)() and then release them in reverse order. In this case you must ensure that any thread aquiring the second lock also calls SpinLockIRQ(or FIQ)() to thereby avoid the deadlock.

It is NOT safe to acquire one lock using SpinLockIRQ(or FIQ)() then another lock using SpinLockIRQ(or FIQ)() and then release them in the SAME order. If the situation absolutely requires this behavious then you must use SpinExchangeIRQ(or FIQ)() when holding both locks in order to reverse the order of the IRQ or FIQ renabling.

Mutex -

A mutually exclusive lock for controlling access to data. Threads yield while waiting to acquire the lock.

Non recursive (can only be acquired once by the same thread) (Recursive if MUTEX_FLAG_RECURSIVE specified)

Not suitable for use by Interrupt handlers.

Suitable for use on multiprocessor systems if the lock is allocated from shared memory (Determined during initialization).

Recommended for long held operations or holding during I/O operations.

Access is not serialized, the next thread to try obtaining the lock when it is released will succeed even if that thread was not the first waiting.

CriticalSection -

A mutually exlusive lock for serializing access to data. Threads are placed on a wait list while waiting to acquire the lock.

Recursive (can be acquired multiple times by the same thread)

Not suitable for use by Interrupt handlers.

Suitable for use on multiprocessor systems.

Recommended for long held operations or holding during I/O operations.

Access is serialized, the next thread to obtain the lock when it is released will be the thread that has been waiting longest.

Semaphore -

Suitable for use by Interrupt handlers for signaling only if created with SEMAPHORE_FLAG_IRQ or FIQ (Interrupt handlers must not call wait).

Suitable for use on multiprocessor systems.

Access is serialized, the next thread to acquire the semaphore when it is signaled will be the thread that has been waiting longest.

Synchronizer -

A reader/writer lock for serializing multiple concurrent reads and single writes to data. Threads are placed on a wait list while waiting to acquire the lock.

Recursive (reader lock can be acquired multiple times by the same thread or by other threads/writer lock can be acquired multiple times by the same thread) Not suitable for use by Interrupt handlers.

Suitable for use on multiprocessor systems.

Recommended for long held operations or holding during I/O operations.

Access is serialized, the next thread to obtain the lock when it is released will be the thread that has been waiting longest.

Constants



Lock flag LOCK_FLAG_*
LOCK_FLAG_NONE = $00000000;  
LOCK_FLAG_IRQ = $00000001;  
LOCK_FLAG_FIQ = $00000002;  
LOCK_FLAG_IRQFIQ = $00000004;  


Spin signature SPIN_SIGNATURE_*
SPIN_SIGNATURE = $0FEC3B82;  


Spin state SPIN_STATE_*
SPIN_STATE_UNLOCKED = 0;  
SPIN_STATE_LOCKED = 1;  


Mutex signature MUTEX_SIGNATURE_*
MUTEX_SIGNATURE = $1C5D7FA4;  


Mutex state MUTEX_STATE_*
MUTEX_STATE_UNLOCKED = 0;  
MUTEX_STATE_LOCKED = 1;  


Mutex flags MUTEX_FLAG_*
MUTEX_FLAG_NONE = $00000000;  
MUTEX_FLAG_RECURSIVE = $00000001;  


Critical section signature CRITICAL_SECTION_SIGNATURE_*
CRITICAL_SECTION_SIGNATURE = $25F3AE01;  


Critical section state CRITICAL_SECTION_STATE_*
CRITICAL_SECTION_STATE_UNLOCKED = 0;  
CRITICAL_SECTION_STATE_LOCKED = 1;  


Semaphore signature SEMAPHORE_SIGNATURE_*
SEMAPHORE_SIGNATURE = $390A1EB4;  


Semaphore flag SEMAPHORE_FLAG_*
SEMAPHORE_FLAG_NONE = LOCK_FLAG_NONE;  
SEMAPHORE_FLAG_IRQ = LOCK_FLAG_IRQ;  
SEMAPHORE_FLAG_FIQ = LOCK_FLAG_FIQ;  
SEMAPHORE_FLAG_IRQFIQ = LOCK_FLAG_IRQFIQ;  


Synchronizer signature SYNCHRONIZER_SIGNATURE_*
SYNCHRONIZER_SIGNATURE = $C5D081FB;  


Synchronizer state SYNCHRONIZER_STATE_*
SYNCHRONIZER_STATE_UNLOCKED = 0;  
SYNCHRONIZER_STATE_READER_LOCKED = 1;  
SYNCHRONIZER_STATE_WRITER_LOCKED = 2;  


Synchronizer flag SYNCHRONIZER_FLAG_*
SYNCHRONIZER_FLAG_NONE = $00000000;  
SYNCHRONIZER_FLAG_READ_PRIORITY = $00000001; Synchronizer prioritises readers over writers
SYNCHRONIZER_FLAG_WRITE_PRIORITY = $00000002; Synchronizer prioritises writers over readers


List signature LIST_SIGNATURE_*
LIST_SIGNATURE = $4A98BE2A;  


List type LIST_TYPE_*
LIST_TYPE_NOT_SPECIFIED = 0; A generic thread list without a specific purpose
LIST_TYPE_WAIT_SECTION = 1; A Critical Section Wait List
LIST_TYPE_WAIT_SEMAPHORE = 2; A Semaphore Wait List
LIST_TYPE_WAIT_SYNCHRONIZER = 3; A Synchronizer Wait List
LIST_TYPE_WAIT_EVENT = 4; An Event Wait List
LIST_TYPE_WAIT_THREAD = 5; A Thread Wait List
LIST_TYPE_WAIT_MESSAGESLOT = 6; A Messageslot Wait List
LIST_TYPE_WAIT_OTHER = 7; Another type of Wait List (Suitable for passing to ThreadWait/ThreadWaitEx/ThreadWaitMultiple/ThreadRelease)


List flag LIST_FLAG_*
LIST_FLAG_NONE = LOCK_FLAG_NONE;  
LIST_FLAG_IRQ = LOCK_FLAG_IRQ;  
LIST_FLAG_FIQ = LOCK_FLAG_FIQ;  
LIST_FLAG_IRQFIQ = LOCK_FLAG_IRQFIQ;  


Queue signature QUEUE_SIGNATURE_*
QUEUE_SIGNATURE = $57A3BF9E;  


Queue type QUEUE_TYPE_*
QUEUE_TYPE_NOT_SPECIFIED = 0; A generic thread queue without a specific purpose
QUEUE_TYPE_SCHEDULE_SLEEP = 1; A Scheduler Sleep Queue
QUEUE_TYPE_SCHEDULE_TIMEOUT = 2; A Scheduler Timeout Queue
QUEUE_TYPE_SCHEDULE_TERMINATION = 3; A Scheduler Termination Queue (Threads are placed on termination queue when they exit or are terminated)
QUEUE_TYPE_SCHEDULE_NONE = 4; A Scheduler No Priority Queue (Only used for IRQ/FIQ threads which are never selected for scheduling)
QUEUE_TYPE_SCHEDULE_IDLE = 5; A Scheduler Idle Priority Queue
QUEUE_TYPE_SCHEDULE_LOWEST = 6; A Scheduler Lowest Priority Queue
QUEUE_TYPE_SCHEDULE_LOWER = 7; A Scheduler Lower Priority Queue
QUEUE_TYPE_SCHEDULE_NORMAL = 8; A Scheduler Normal Priority Queue
QUEUE_TYPE_SCHEDULE_HIGHER = 9; A Scheduler Higher Priority Queue
QUEUE_TYPE_SCHEDULE_HIGHEST = 10; A Scheduler Highest Priority Queue
QUEUE_TYPE_SCHEDULE_CRITICAL = 11; A Scheduler Critical Priority Queue


Queue flag QUEUE_FLAG_*
NONE = LOCK_FLAG_NONE;  
QUEUE_FLAG_IRQ = LOCK_FLAG_IRQ;  
QUEUE_FLAG_FIQ = LOCK_FLAG_FIQ;  
QUEUE_FLAG_IRQFIQ = LOCK_FLAG_IRQFIQ;  
QUEUE_FLAG_DESCENDING = $00000008;  
QUEUE_FLAG_DELTA = $00000010;  


Queue key QUEUE_KEY_*
QUEUE_KEY_NONE = Integer($7FFFFFFF); Null key value returned from an empty Queue
QUEUE_KEY_MAX = Integer($7FFFFFFE); Max key that can be ordered in a Queue
QUEUE_KEY_MIN = Integer($80000000); Min key that can be ordered in a Queue


Thread signature THREAD_SIGNATURE_*
THREAD_SIGNATURE = $6C2BA10F;  


Thread type THREAD_TYPE_*
THREAD_TYPE_NORMAL = 0; A Normal thread (No special case handling)
THREAD_TYPE_IDLE = 1; An Idle thread (Used to calculate ultilization and provide an always ready thread)
THREAD_TYPE_IRQ = 2; An IRQ thread (Used by the IRQ handler during interrupt time)
THREAD_TYPE_FIQ = 3; An FIQ thread (Used by the FIQ handler during interrupt time)
THREAD_TYPE_SWI = 4; A Software Interrupt (SWI) thread (Used by the SWI handler during a system call)


Thread state THREAD_STATE_*
THREAD_STATE_RUNNING = 1; Thread is currently running
THREAD_STATE_READY = 2; Thread is on ready queue
THREAD_STATE_SLEEP = 3; Thread is sleeping
THREAD_STATE_SUSPENDED = 4; Thread is suspended
THREAD_STATE_WAIT = 5; Thread is on a wait list
THREAD_STATE_WAIT_TIMEOUT = 6; Thread is on a wait list with timeout
THREAD_STATE_RECEIVE = 7; Thread is waiting to receive a message
THREAD_STATE_RECEIVE_TIMEOUT = 8; Thread is waiting to receive a message with timeout
THREAD_STATE_HALTED = 9; Thread has been halted (Due to an unhandled exception etc)
THREAD_STATE_TERMINATED = 10; Thread has been terminated


Thread priority THREAD_PRIORITY_*
THREAD_PRIORITY_NONE = 0; Only used for IRQ/FIQ threads which are never selected for scheduling
THREAD_PRIORITY_IDLE = 1;  
THREAD_PRIORITY_LOWEST = 2;  
THREAD_PRIORITY_LOWER = 3;  
THREAD_PRIORITY_NORMAL = 4;  
THREAD_PRIORITY_HIGHER = 5;  
THREAD_PRIORITY_HIGHEST = 6;  
THREAD_PRIORITY_CRITICAL = 7;  
 
THREAD_PRIORITY_DEFAULT = THREAD_PRIORITY_NORMAL; Default thread priority
THREAD_PRIORITY_MINIMUM = THREAD_PRIORITY_IDLE; Minimum thread priority
THREAD_PRIORITY_MAXIMUM = THREAD_PRIORITY_CRITICAL; Maximum thread priority
THREAD_PRIORITY_COUNT = THREAD_PRIORITY_MAXIMUM + 1; Number of thread priority levels
 
Additional priority aliases for compatibility
THREAD_PRIORITY_BELOW_NORMAL = THREAD_PRIORITY_LOWER;  
THREAD_PRIORITY_ABOVE_NORMAL = THREAD_PRIORITY_HIGHER;  
THREAD_PRIORITY_TIME_CRITICAL = THREAD_PRIORITY_CRITICAL;  


Thread name THREAD_NAME_*
THREAD_NAME_LENGTH = 256; Length of thread name
 
IRQ_THREAD_NAME = 'IRQ';  
FIQ_THREAD_NAME = 'FIQ';  
SWI_THREAD_NAME = 'SWI';  
IDLE_THREAD_NAME = 'Idle';  
MAIN_THREAD_NAME = 'Main';  
TIMER_THREAD_NAME = 'Timer';  
WORKER_THREAD_NAME = 'Worker';  
TIMER_PRIORITY_THREAD_NAME = 'Priority Timer';  
WORKER_PRIORITY_THREAD_NAME = 'Priority Worker';  
RTL_THREAD_NAME = 'RTL Thread';  


Thread priority *_THREAD_PRIORITY
TIMER_THREAD_PRIORITY = THREAD_PRIORITY_NORMAL;  
WORKER_THREAD_PRIORITY = THREAD_PRIORITY_NORMAL;  
TIMER_PRIORITY_THREAD_PRIORITY = THREAD_PRIORITY_HIGHEST;  
WORKER_PRIORITY_THREAD_PRIORITY = THREAD_PRIORITY_HIGHER;  


Thread create THREAD_CREATE_*
THREAD_CREATE_NONE = $00000000;  
THREAD_CREATE_SUSPENDED = $00000004;  


Thread TLS THREAD_TLS_*
THREAD_TLS_FREE = $00000000;  
THREAD_TLS_USED = $00000001;  
THREAD_TLS_INVALID = $FFFFFFFF;  
 
THREAD_TLS_MAXIMUM = SIZE_64; The maximum number TLS index slots available


Thread TLS flag THREAD_TLS_FLAG_*
THREAD_TLS_FLAG_NONE = $00000000;  
THREAD_TLS_FLAG_FREE = $00000001; If set then pointer in thread TLS index will be freed on ThreadReleaseTlsIndex or ThreadDestroy


Thread wait THREAD_LISTS_*
THREAD_LISTS_MAXIMUM = SIZE_64; Maximum number of lists a thread can wait on at the same time


Messageslot signature MESSAGESLOT_SIGNATURE_*
MESSAGESLOT_SIGNATURE = $B631CE4B;  


Messageslot flag MESSAGESLOT_FLAG_*
MESSAGESLOT_FLAG_NONE = LOCK_FLAG_NONE;  
MESSAGESLOT_FLAG_IRQ = LOCK_FLAG_IRQ;  
MESSAGESLOT_FLAG_FIQ = LOCK_FLAG_FIQ;  
MESSAGESLOT_FLAG_IRQFIQ = LOCK_FLAG_IRQFIQ;  


Mailslot signature MAILSLOT_SIGNATURE_*
MAILSLOT_SIGNATURE = $7A409BF3;  


Buffer signature BUFFER_SIGNATURE_*
BUFFER_SIGNATURE = $830BEA71;  


Buffer flag BUFFER_FLAG_*
BUFFER_FLAG_NONE = $00000000;  
BUFFER_FLAG_SHARED = $00000001; If set the buffer memory (Not the buffer entry itself) is allocated from shared memory


Event signature EVENT_SIGNATURE_*
EVENT_SIGNATURE = $903BA69D;  


Event state EVENT_STATE_*
EVENT_STATE_UNSIGNALED = 0;  
EVENT_STATE_SIGNALED = 1;  


Event flag EVENT_FLAG_*
EVENT_FLAG_NONE = $00000000;  
EVENT_FLAG_INITIAL_STATE = $00000001;  
EVENT_FLAG_MANUAL_RESET = $00000002;  


Timer signature TIMER_SIGNATURE_*
TIMER_SIGNATURE = $AB7E07FB;  


Timer state TIMER_STATE_*
TIMER_STATE_DISABLED = 0;  
TIMER_STATE_ENABLED = 1;  


Timer flag TIMER_FLAG_*
TIMER_FLAG_NONE = $00000000;  
TIMER_FLAG_RESCHEDULE = $00000001; Timer should be rescheduled each time the event completes
TIMER_FLAG_IMMEDIATE = $00000002; Timer event should be executed immediately and then each interval milliseconds
TIMER_FLAG_WORKER = $00000004; Timer event should be executed by a worker thread instead of a timer thread
TIMER_FLAG_PRIORITY = $00000008; Timer event should be executed by a priority timer thread


Timer key TIMER_KEY_*
TIMER_KEY_NONE = Integer($7FFFFFFF); Null key value returned from an empty Timer list
TIMER_KEY_MAX = Integer($7FFFFFFE); Max key that can be ordered in a Timer list
TIMER_KEY_MIN = Integer($80000000); Min key that can be ordered in a Timer list


Worker signature WORKER_SIGNATURE_*
WORKER_SIGNATURE = $EF6A901B;  


Worker flag WORKER_FLAG_*
WORKER_FLAG_NONE = $00000000;  
WORKER_FLAG_RESCHEDULE = $00000001; Worker task should be rescheduled each time the task completes
WORKER_FLAG_IMMEDIATE = $00000002; Worker task should be executed immediately and then each interval milliseconds
WORKER_FLAG_CANCEL = $00000004; Internal flag to indicate the worker task should be cancelled next time the interval expires
WORKER_FLAG_NOFREE = $00000008; Internal flag to tell worker execute not to free the worker request when it is completed
WORKER_FLAG_TERMINATE = $00000010; Internal flag to tell worker execute to terminate the worker thread
WORKER_FLAG_IRQ = $00000020; Internal flag to tell worker execute to free IRQ memory when the request is completed
WORKER_FLAG_FIQ = $00000040; Internal flag to tell worker execute to free FIQ memory when the request is completed
WORKER_FLAG_PRIORITY = $00000080; Worker task should be executed by a priority worker thread
 
WORKER_FLAG_INTERNAL = WORKER_FLAG_CANCEL or WORKER_FLAG_NOFREE or WORKER_FLAG_TERMINATE or WORKER_FLAG_IRQ or WORKER_FLAG_FIQ; Internal only flags
 
WORKER_FLAG_EXCLUDED_IRQ = WORKER_FLAG_RESCHEDULE or WORKER_FLAG_IMMEDIATE; Excluded flags
WORKER_FLAG_EXCLUDED_FIQ = WORKER_FLAG_RESCHEDULE or WORKER_FLAG_IMMEDIATE; Excluded flags


Tasker task TASKER_TASK_*
TASKER_TASK_THREADSENDMESSAGE = 1; Perform a ThreadSendMessage() function using the tasker list
TASKER_TASK_MESSAGESLOTSEND = 2; Perform a MessageslotSend() function using the tasker list
TASKER_TASK_SEMAPHORESIGNAL = 3; Perform a SemaphoreSignal() function using the tasker list


Scheduler migration SCHEDULER_MIGRATION_*
SCHEDULER_MIGRATION_DISABLED = 0;  
SCHEDULER_MIGRATION_ENABLED = 1;  


Scheduler preempt SCHEDULER_PREEMPT_*
SCHEDULER_PREEMPT_DISABLED = 0;  
SCHEDULER_PREEMPT_ENABLED = 1;  


Scheduler allocation SCHEDULER_ALLOCATION_*
SCHEDULER_ALLOCATION_DISABLED = 0;  
SCHEDULER_ALLOCATION_ENABLED = 1;  


Scheduler mask SCHEDULER_MASK_*
SCHEDULER_MASK_NONE = (1 shl THREAD_PRIORITY_NONE);  
SCHEDULER_MASK_IDLE = (1 shl THREAD_PRIORITY_IDLE);  
SCHEDULER_MASK_LOWEST = (1 shl THREAD_PRIORITY_LOWEST);  
SCHEDULER_MASK_LOWER = (1 shl THREAD_PRIORITY_LOWER);  
SCHEDULER_MASK_NORMAL = (1 shl THREAD_PRIORITY_NORMAL);  
SCHEDULER_MASK_HIGHER = (1 shl THREAD_PRIORITY_HIGHER);  
SCHEDULER_MASK_HIGHEST = (1 shl THREAD_PRIORITY_HIGHEST);  
SCHEDULER_MASK_CRITICAL = (1 shl THREAD_PRIORITY_CRITICAL);  


Scheduler quantum SCHEDULER_QUANTUM_*
SCHEDULER_QUANTUM_NONE = 0;  
SCHEDULER_QUANTUM_IDLE = 0;  
SCHEDULER_QUANTUM_LOWEST = 1;  
SCHEDULER_QUANTUM_LOWER = 2;  
SCHEDULER_QUANTUM_NORMAL = 4;  
SCHEDULER_QUANTUM_HIGHER = 6;  
SCHEDULER_QUANTUM_HIGHEST = 8;  
SCHEDULER_QUANTUM_CRITICAL = 10;  


Thread logging THREAD_LOG_*
THREAD_LOG_LEVEL_DEBUG = LOG_LEVEL_DEBUG; Thread debugging messages
THREAD_LOG_LEVEL_INFO = LOG_LEVEL_INFO; Thread informational messages, such as a thread being created or destroyed
THREAD_LOG_LEVEL_ERROR = LOG_LEVEL_ERROR; Thread error messages
THREAD_LOG_LEVEL_NONE = LOG_LEVEL_NONE; No Thread messages


Type definitions



Spin entry

PSpinEntry = ^TSpinEntry;

TSpinEntry = record

Spin Properties
Signature:LongWord; Signature for entry validation
State:LongWord; State of the lock (Locked/Unlocked)
Mask:LongWord; IRQ/FIQ Mask for Save/Restore
Owner:TThreadHandle; Currently owning thread (or INVALID_HANDLE_VALUE if not locked)
Internal Properties
Prev:PSpinEntry; Previous entry in Spin table
Next:PSpinEntry; Next entry in Spin table
Statistics Properties
   

Mutex entry

PMutexEntry = ^TMutexEntry;

TMutexEntry = record

Mutex Properties
Signature:LongWord; Signature for entry validation
State:LongWord; State of the lock (Locked/Unlocked)
Owner:TThreadHandle; Currently owning thread (or INVALID_HANDLE_VALUE if not locked)
Yield:TThreadYield; Yield function to call while waiting
Count:LongWord; Count of lock recursions (only if Flags includes MUTEX_FLAG_RECURSIVE)
Flags:LongWord; Mutex Flags (eg MUTEX_FLAG_RECURSIVE)
SpinCount:LongWord; Number of times to spin wait for lock before Yield is called (Always 0 if SCHEDULER_CPU_COUNT = 1)
Internal Properties
Prev:PMutexEntry; Previous entry in Mutex table
Next:PMutexEntry; Next entry in Mutex table
Statistics Properties
   

Critical section entry

PCriticalSectionEntry = ^TCriticalSectionEntry;

TCriticalSectionEntry = record

Critical Section Properties
Signature:LongWord; Signature for entry validation
State:LongWord; State of the lock (Locked/Unlocked)
Count:LongWord; Count of lock recursions
Owner:TThreadHandle; Currently owning thread (or INVALID_HANDLE_VALUE if not locked)
SpinCount:LongWord; Number of times to spin wait for lock before Wait is called (Always 0 if SCHEDULER_CPU_COUNT = 1)
Lock:TSpinHandle; Critical Section Lock
List:TListHandle; List of threads waiting on this CriticalSection (or INVALID_HANDLE_VALUE if never used)
Wait:TThreadWait; Wait function to call to wait on the CriticalSection if it is already locked
WaitEx:TThreadWaitEx; Wait function to call to wait with timeout on the CriticalSection if it is already locked
Release:TThreadRelease; Release function to call if any threads are waiting when CriticalSection is unlocked
Abandon:TThreadAbandon; Abandon function to call if any threads are waiting when CriticalSection is destroyed
Internal Properties
Prev:PCriticalSectionEntry; Previous entry in CriticalSection table
Next:PCriticalSectionEntry; Next entry in CriticalSection table
Statistics Properties
   

Semaphore entry

PSemaphoreEntry = ^TSemaphoreEntry;

TSemaphoreEntry = record

Semaphore Properties
Signature:LongWord; Signature for entry validation
Count:LongWord; Count for this Semaphore (Can be negative when Threads are waiting)
Maximum:LongWord; Maximum count for this Semaphore
Flags:LongWord; Semaphore Flags (eg SEMAPHORE_FLAG_IRQ)
Lock:TSpinHandle; Semaphore Lock
List:TListHandle; List of threads waiting on this Semaphore (or INVALID_HANDLE_VALUE if never used)
Wait:TThreadWait; Wait function to call to wait on the Semaphore if the count is equal to zero on SemaphoreWait
WaitEx:TThreadWaitEx; Wait function to call to wait with timeout on the Semaphore if the count is equal to zero on SemaphoreWait
Release:TThreadRelease; Release function to call if any threads are waiting on SemaphoreSignal
Abandon:TThreadAbandon; Abandon function to call if any threads are waiting when SemaphoreSignal is destroyed
Internal Properties
Prev:PSemaphoreEntry; Previous entry in Semaphore table
Next:PSemaphoreEntry; Next entry in Semaphore table
Statistics Properties
   

Synchronizer entry

PSynchronizerEntry = ^TSynchronizerEntry;

TSynchronizerEntry = record

Synchronizer Properties
Signature:LongWord; Signature for entry validation
State:LongWord; State of the lock (Locked/Unlocked)
Lock:TSpinHandle; Synchronizer Lock
ReaderCount:LongWord; Count of current reader locks
WriterCount:LongWord; Count of current writer lock recursions
ReaderLast:TThreadHandle; Last thread to acquire reader lock (or INVALID_HANDLE_VALUE if no reader)
WriterOwner:TThreadHandle; Currently owning writer thread (or INVALID_HANDLE_VALUE if no writer)
ReaderList:TListHandle; List of reader threads waiting on this Synchronizer (or INVALID_HANDLE_VALUE if never used)
WriterList:TListHandle; List of writer threads waiting on this Synchronizer (or INVALID_HANDLE_VALUE if never used)
Wait:TThreadWait; Wait function to call to wait on the Synchronizer if it is already locked
WaitEx:TThreadWaitEx; Wait function to call to wait with timeout on the Synchronizer if it is already locked
Release:TThreadRelease; Release function to call if any threads are waiting when Synchronizer is unlocked
Abandon:TThreadAbandon; Abandon function to call if any threads are waiting when Synchronizer is destroyed
Internal Properties
Prev:PSynchronizerEntry; Previous entry in Synchronizer table
Next:PSynchronizerEntry; Next entry in Synchronizer table
Statistics Properties
   

List entry

PListEntry = ^TListEntry;

TListEntry = record

List Properties
Signature:LongWord; Signature for entry validation
ListType:LongWord; Type of this List (eg LIST_TYPE_WAIT_SECTION)
Count:LongWord; Count of items currently in this List
Flags:LongWord; List Flags (eg LIST_FLAG_IRQ)
Lock:TSpinHandle; List Lock
First:PListElement; First element in List
Last:PListElement; Last element in List
Internal Properties
Prev:PListEntry; Previous entry in List table
Next:PListEntry; Next entry in List table
Statistics Properties
   

List element

PListElement = ^TListElement;

TListElement = record

Thread:TThreadHandle; The thread referenced by this List element
Prev:PListElement; Previous element in List
Next:PListElement; Next element in List

List handles

PListHandles = ^TListHandles;

TListHandles = array[0..THREAD_LISTS_MAXIMUM - 1] of TListHandle;

   

Queue entry

PQueueEntry = ^TQueueEntry;

TQueueEntry = record

Queue Properties
Signature:LongWord; Signature for entry validation
QueueType:LongWord; Type of this Queue (eg QUEUE_TYPE_SCHEDULE_IDLE)
Count:LongWord; Count of items currently in this Queue
Flags:LongWord; Queue Flags (eg QUEUE_FLAG_IRQ)
Lock:TSpinHandle; Queue Lock
First:PQueueElement; First element in Queue
Last:PQueueElement; Last element in Queue
Internal Properties
Prev:PQueueEntry; Previous entry in Queue table
Next:PQueueEntry; Next entry in Queue table
Statistics Properties
   

Queue element

PQueueElement = ^TQueueElement;

TQueueElement = record

Key:Integer; Ordering key for Queue
Thread:TThreadHandle; The thread referenced by this Queue element
Prev:PQueueElement; Previous element in Queue
Next:PQueueElement; Next element in Queue

Message list

PMessageList = ^TMessageList;

TMessageList = record

Header Properties
Maximum:LongWord; Maximum number of messages in list
Count:LongWord; Current number of messages in list
Start:LongWord; First message available in list
Internal Properties
List:PMessage; Message list
Statistics Properties
   

Message

PMessage = ^TMessage;

TMessage = record

Msg:LongWord;  
wParam:LongInt;  
lParam:LongInt;  
Time:LongWord;  

Thread entry

PThreadEntry = ^TThreadEntry;

TThreadEntry = record

Thread Properties
Signature:LongWord; Signature for entry validation
State:LongWord; State of the Thread (eg THREAD_STATE_RUNNING)
Priority:LongWord; Priority of the Thread (eg THREAD_PRIORITY_NORMAL)
Affinity:LongWord; CPU Affinity mask of the Thread
StackBase:Pointer; Base (Top) of the thread stack
StackSize:LongWord; Stack length in bytes
Name:array[0..THREAD_NAME_LENGTH - 1] of Char; The name of the Thread
Lock:TSpinHandle; Thread Lock
Parent:TThreadHandle; Handle of the parent thread
Messages:TMessageList; Messages sent to this thread
TlsPointer:Pointer; Thread Local Storage Memory (RTL ThreadVars)
TlsTable:array[0..THREAD_TLS_MAXIMUM - 1] of Pointer; Thread Local Storage Index Pointers (for ThreadGetTlsValue/ThreadSetTlsValue)
TlsFlags:array[0..THREAD_TLS_MAXIMUM - 1] of LongWord; Thread Local Storage Index Flags (eg THREAD_TLS_FLAG_FREE)
ExitCode:LongWord; Thread Exit Code
LastError:LongWord; Thread Last Error
Locale:LCID; Thread Locale
Internal Properties
CurrentCPU:LongWord; Saved current CPU from last ContextSwitch
StackPointer:Pointer; Saved current stack pointer from last ContextSwitch
TargetCPU:LongWord; Target CPU of the Thread for next ContextSwitch
TargetPriority:LongWord; Target Priority of the Thread for next ContextSwitch (eg THREAD_PRIORITY_NORMAL)
List:TListHandle; List of threads waiting on this thread (or INVALID_HANDLE_VALUE if never used)
WaitList:TListHandle; The wait list this thread is currently in (or INVALID_HANDLE_VALUE)
WaitLists:PListHandles; The wait lists this thread is currently in if doing a multiple wait (or nil)
WaitResult:LongWord; The result code for the last wait with timeout (eg WAIT_TIMEOUT)
ReceiveResult:LongWord; The result code for the last receive with timeout (eg WAIT_TIMEOUT)
 
ListElement:TListElement; List element for this thread when in a Wait List
QueueElement:TQueueElement; Queue element for this thread when in a Schedule Queue
Prev:PThreadEntry; Previous entry in Thread table
Next:PThreadEntry; Next entry in Thread table
Statistics Properties
CreateTime:Int64; The time when this thread was created
ExitTime:Int64; The time when this thread exited or was terminated
KernelTime:Int64; The total amount of time this thread has been in the running state (ie CPU time consumed)
SwitchCount:Int64; The number of times this thread has been selected to run by a context switch

Thread snapshot

PThreadSnapshot = ^TThreadSnapshot;

TThreadSnapshot = record

Note: Data returned by ThreadSnapshotCreate
Snapshot Properties
Handle:TThreadHandle; Handle of the thread
State:LongWord; State of the Thread (eg THREAD_STATE_RUNNING)
CPU:LongWord; CPU from last ContextSwitch
Priority:LongWord; Priority of the Thread (eg THREAD_PRIORITY_NORMAL)
Affinity:LongWord; CPU Affinity mask of the Thread
StackBase:Pointer; Base (Top) of the thread stack
StackSize:LongWord; Stack length in bytes
StackPointer:Pointer; Stack pointer from last ContextSwitch
Name:array[0..THREAD_NAME_LENGTH - 1] of Char; The name of the Thread
Parent:TThreadHandle; Handle of the parent thread
ExitCode:LongWord; Thread Exit Code
LastError:LongWord; Thread Last Error
Locale:LCID; Thread Locale
TargetCPU:LongWord; Target CPU of the Thread for next ContextSwitch
TargetPriority:LongWord; Target Priority of the Thread for next ContextSwitch (eg THREAD_PRIORITY_NORMAL)
CreateTime:Int64; The time when this thread was created
ExitTime:Int64; The time when this thread exited or was terminated
KernelTime:Int64; The total amount of time this thread has been in the running state (ie CPU time consumed)
SwitchCount:Int64; The number of times this thread has been selected to run by a context switch
Internal Properties
Next:PThreadSnapshot; Next entry in Thread snapshot

Messageslot entry

PMessageslotEntry = ^TMessageslotEntry;

TMessageslotEntry = record

Messageslot Properties
Signature:LongWord; Signature for entry validation
Flags:LongWord; Messageslot Flags (eg MESSAGESLOT_FLAG_IRQ)
Lock:TSpinHandle; Messageslot Lock
List:TListHandle; List of threads waiting on this Messageslot (or INVALID_HANDLE_VALUE if never used)
Messages:TMessageList; Messageslot message queue
Wait:TThreadWait; Wait function to call to wait on the Messageslot if there are no messages
WaitEx:TThreadWaitEx; Wait function to call to wait with timeout on the Messageslot if there are no messages
Release:TThreadRelease; Release function to call if any threads are waiting when a message is sent
Abandon:TThreadAbandon; Abandon function to call if any threads are waiting when Messageslot is destroyed
Internal Properties
Prev:PMessageslotEntry; Previous entry in Messageslot table
Next:PMessageslotEntry; Next entry in Messageslot table
Statistics Properties
   

Mailslot entry

PMailslotEntry = ^TMailslotEntry;

TMailslotEntry = record

Mailslot Properties
Signature:LongWord; Signature for entry validation
Maximum:LongWord; Maximum number of messages in Mailslot
Count:LongWord; Current number of messages in Mailslot
Start:LongWord; First message available in Mailslot
Lock:TSpinHandle; Mailslot Lock
Sender:TSemaphoreHandle; Mailslot send Semaphore
Receiver:TSemaphoreHandle; Mailslot receive Semaphore
Messages:PInteger; Mailslot message queue
Internal Properties
Prev:PMailslotEntry; Previous entry in Mailslot table
Next:PMailslotEntry; Next entry in Mailslot table
Statistics Properties
   

Buffer entry

PBufferEntry = ^TBufferEntry;

TBufferEntry = record

Buffer Properties
Signature:LongWord; Signature for entry validation
Size:LongWord; Size of each buffer
Count:LongWord; Number of buffers
Flags:LongWord; Buffer Flags (eg BUFFER_FLAG_SHARED)
Lock:TSpinHandle; Buffer Lock
Available:TSemaphoreHandle; Buffer available Semaphore
Buffers:PBufferItem; Buffer list
Internal Properties
Prev:PBufferEntry; Previous entry in Buffer table
Next:PBufferEntry; Next entry in Buffer table
First:PBufferItem; First available buffer item
Statistics Properties
   

Buffer item

PBufferItem = ^TBufferItem;

TBufferItem = record

Parent:TBufferHandle; Handle of Buffer owning this item
Next:PBufferItem; Next item in list
Buffer:Pointer; Pointer to item data
Reserved:LongWord; Align to 16 bytes

Event entry

PEventEntry = ^TEventEntry;

TEventEntry = record

Event Properties
Signature:LongWord; Signature for entry validation
State:LongWord; State of the event (Signaled/Unsignaled)
Flags:LongWord; Event Flags (eg EVENT_FLAG_MANUAL)
Lock:TSpinHandle; Event Lock
List:TListHandle; List of threads waiting on this Event (or INVALID_HANDLE_VALUE if never used)
Wait:TThreadWait; Wait function to call to wait on the Event if it is not Signaled
WaitEx:TThreadWaitEx; Wait function to call to wait with timeout on the Event if it is not Signaled
Release:TThreadRelease; Release function to call if any threads are waiting when Event is Signaled
Abandon:TThreadAbandon; Abandon function to call if any threads are waiting when Event is destroyed
Internal Properties
Prev:PEventEntry; Previous entry in Event table
Next:PEventEntry; Next entry in Event table
Statistics Properties
   

Timer list

PTimerList = ^TTimerList;

TTimerList = record

List Properties
Count:LongWord; Count of items currently in the Timer list
Flags:LongWord; Timer list Flags (eg LOCK_FLAG_IRQ)
Lock:TSpinHandle; Timer list Lock
First:PTimerItem; First item in Timer list
Last:PTimerItem; Last item in Timer list
Internal Properties
   
Statistics Properties
   

Timer item

PTimerItem = ^TTimerItem;

TTimerItem = record

Key:Integer; Ordering key for Timer list
Timer:TTimerHandle; The timer referenced by this Timer list item
Prev:PTimerItem; Previous item in Timer list
Next:PTimerItem; Next item in Timer list

Timer entry

PTimerEntry = ^TTimerEntry;

TTimerEntry = record

Timer Properties
Signature:LongWord; Signature for entry validation
Interval:LongWord; Interval for timer (Milliseconds)
State:LongWord; State of the timer (Enabled/Disabled)
Flags:LongWord; Timer Flags (eg TIMER_FLAG_RESCHEDULE)
Lock:TSpinHandle; Timer Lock
Event:TTimerEvent; Function to call when timer triggers
Data:Pointer; Data to pass to function when timer triggers
Internal Properties
TimerList:PTimerList; The timer list this timer is currently in (or nil)
TimerItem:TTimerItem; Timer list item for this timer when in a Timer list
Prev:PTimerEntry; Previous entry in Timer table
Next:PTimerEntry; Next entry in Timer table
Statistics Properties
   

Worker request

PWorkerRequest = ^TWorkerRequest;

TWorkerRequest = record

Worker Properties
Signature:LongWord; Signature for entry validation
Interval:LongWord; Interval for worker (Milliseconds)
Flags:LongWord; Worker Flags (eg WORKER_FLAG_RESCHEDULE)
Lock:TSpinHandle; Worker Lock (or INVALID_HANDLE_VALUE if Interval is 0 and Flags is not WORKER_FLAG_RESCHEDULE)
Timer:TTimerHandle; Worker Timer (or INVALID_HANDLE_VALUE if Interval is 0)
Task:TWorkerTask; Task to call by worker
Data:Pointer; Data to pass to task
Callback:TWorkerCallback; Callback when task is completed

Tasker list

PTaskerList = ^TTaskerList;

TTaskerList = record

List Properties
Count:LongWord; Count of tasks currently in the Tasker list
Lock:TSpinHandle; Tasker list Lock
First:PTaskerTask; First task in Tasker list
Last:PTaskerTask; Last task in Tasker list
Internal Properties
   
Statistics Properties
   

Tasker task

PTaskerTask = ^TTaskerTask;

TTaskerTask = record

Task:LongWord; The task to be performed
Prev:PTaskerTask; Previous task in Tasker list
Next:PTaskerTask; Next task in Tasker list

Tasker thread send message

PTaskerThreadSendMessage = ^TTaskerThreadSendMessage;

TTaskerThreadSendMessage = record

Task:LongWord; The task to be performed
Prev:PTaskerTask; Previous task in Tasker list
Next:PTaskerTask; Next task in Tasker list
Internal Properties
Thread:TThreadHandle; Handle of the thread to send a message to
Message:TMessage; Message to send to the thread

Tasker messageslot send

PTaskerMessageslotSend = ^TTaskerMessageslotSend;

TTaskerMessageslotSend = record

Task:LongWord; The task to be performed
Prev:PTaskerTask; Previous task in Tasker list
Next:PTaskerTask; Next task in Tasker list
Internal Properties
Messageslot:TMessageslotHandle; Handle of the messageslot to send to
Message:TMessage; Message to be sent

Tasker semaphore signal

PTaskerSemaphoreSignal = ^TTaskerSemaphoreSignal;

TTaskerSemaphoreSignal = record

Task:LongWord; The task to be performed
Prev:PTaskerTask; Previous task in Tasker list
Next:PTaskerTask; Next task in Tasker list
Internal Properties
Semaphore:TSemaphoreHandle; Handle of the semaphore to signal
Count:LongWord; The count to be signalled

Thread info

PThreadInfo = ^TThreadInfo;

TThreadInfo = record

ThreadFunction:TThreadFunc;  
ThreadParameter:Pointer;  
StackLength:Cardinal;  

CPU start

TCPUStart = procedure(CPUID:LongWord);

Primary initialization

TPrimaryInit = procedure;

Scheduler initialization

TSchedulerInit = procedure;

Scheduler start

TSchedulerStart = procedure(CPUID:LongWord);

Secondary initialization

TSecondaryInit = procedure;

Secondary boot

TSecondaryBoot = procedure(CPUID:LongWord);

Spin lock

TSpinLock = function(Spin:PSpinEntry):LongWord;

Spin unlock

TSpinUnlock = function(Spin:PSpinEntry):LongWord;

Spin lock IRQ

TSpinLockIRQ = function(Spin:PSpinEntry):LongWord;

Spin unlock IRQ

TSpinUnlockIRQ = function(Spin:PSpinEntry):LongWord;

Spin lock FIQ

TSpinLockFIQ = function(Spin:PSpinEntry):LongWord;

Spin unlock FIQ

TSpinUnlockFIQ = function(Spin:PSpinEntry):LongWord;

Spin lock IRQ/FIQ

TSpinLockIRQFIQ = function(Spin:PSpinEntry):LongWord;

Spin unlock IRQ/FIQ

TSpinUnlockIRQFIQ = function(Spin:PSpinEntry):LongWord;

Spin check IRQ

TSpinCheckIRQ = function(Spin:PSpinEntry):Boolean;

Spin check FIQ

TSpinCheckFIQ = function(Spin:PSpinEntry):Boolean;

Spin exchange IRQ

TSpinExchangeIRQ = function(Spin1,Spin2:PSpinEntry):LongWord;

Spin exchange FIQ

TSpinExchangeFIQ = function(Spin1,Spin2:PSpinEntry):LongWord;

Spin mask exchange

TSpinMaskExchange = function(Spin1,Spin2:PSpinEntry):LongWord;

Mutex lock

TMutexLock = function(Mutex:PMutexEntry):LongWord;

Mutex unlock

TMutexUnlock = function(Mutex:PMutexEntry):LongWord;

Mutex try lock

TMutexTryLock = function(Mutex:PMutexEntry):LongWord;

Critical section lock

TCriticalSectionLock = function(CriticalSection:PCriticalSectionEntry):LongWord;

Critical section lock ex

TCriticalSectionLockEx = function(CriticalSection:PCriticalSectionEntry; Timeout:LongWord):LongWord;

Critical section unlock

TCriticalSectionUnlock = function(CriticalSection:PCriticalSectionEntry):LongWord;

Critical section try lock

TCriticalSectionTryLock = function(CriticalSection:PCriticalSectionEntry):LongWord;

Semaphore wait

TSemaphoreWait = function(Semaphore:PSemaphoreEntry):LongWord;

Semaphore wait ex

TSemaphoreWaitEx = function(Semaphore:PSemaphoreEntry; Timeout:LongWord):LongWord;

Semaphore signal

TSemaphoreSignal = function(Semaphore:PSemaphoreEntry):LongWord;

Synchronizer lock

TSynchronizerLock = function(Synchronizer:PSynchronizerEntry):LongWord;

Synchronizer lock ex

TSynchronizerLockEx = function(Synchronizer:PSynchronizerEntry; Timeout:LongWord):LongWord;

Synchronizer unlock

TSynchronizerUnlock = function(Synchronizer:PSynchronizerEntry):LongWord;

Synchronizer convert

TSynchronizerConvert = function(Synchronizer:PSynchronizerEntry):LongWord;

Synchronizer convert ex

TSynchronizerConvertEx = function(Synchronizer:PSynchronizerEntry; Timeout:LongWord):LongWord;

Messageslot send

TMessageslotSend = function(Messageslot:PMessageslotEntry; Message:PMessage):LongWord;

Messageslot receive

TMessageslotReceive = function(Messageslot:PMessageslotEntry; Message:PMessage):LongWord;

Messageslot receive ex

TMessageslotReceiveEx = function(Messageslot:PMessageslotEntry; Message:PMessage; Timeout:LongWord):LongWord;

Mailslot send

TMailslotSend = function(Mailslot:PMailslotEntry; Data:Integer):LongWord;

Mailslot send ex

TMailslotSendEx = function(Mailslot:PMailslotEntry; Data:Integer; Timeout:LongWord):LongWord;

Mailslot receive

TMailslotReceive = function(Mailslot:PMailslotEntry):Integer;

Mailslot receive ex

TMailslotReceiveEx = function(Mailslot:PMailslotEntry; Timeout:LongWord):Integer;

Buffer get

TBufferGet = function(Buffer:PBufferEntry):Pointer;

Buffer get ex

TBufferGetEx = function(Buffer:PBufferEntry; Timeout:LongWord):Pointer;

Buffer free

TBufferFree = function(Buffer:Pointer):LongWord;

Buffer iterate

TBufferIterate = function(Buffer:PBufferEntry; Previous:Pointer):Pointer;

Event wait

TEventWait = function(Event:PEventEntry):LongWord;

Event wait ex

TEventWaitEx = function(Event:PEventEntry; Timeout:LongWord):LongWord;

Event set

TEventSet = function(Event:PEventEntry):LongWord;

Event reset

TEventReset = function(Event:PEventEntry):LongWord;

Event pulse

TEventPulse = function(Event:PEventEntry):LongWord;

Timer enable

TTimerEnable = function(Timer:PTimerEntry):LongWord;

Timer enable ex

TTimerEnableEx = function(Timer:PTimerEntry; Interval:LongWord; Event:TTimerEvent; Data:Pointer):LongWord;

Timer disable

TTimerDisable = function(Timer:PTimerEntry):LongWord;

Timer check

TTimerCheck = function:LongWord;

Timer trigger

TTimerTrigger = function:LongWord;

Tasker check

TTaskerCheck = function:LongWord;

Tasker trigger

TTaskerTrigger = function:LongWord;

Thread get current

TThreadGetCurrent = function:TThreadHandle;

Thread set current

TThreadSetCurrent = function(Thread:TThreadHandle):LongWord;

Thread start

TThreadStart = function(Parameter:Pointer):PtrInt;

Thread end

TThreadEnd = procedure(ExitCode:LongWord);

Scheduler check

TSchedulerCheck = function(CPUID:LongWord):LongWord;

Scheduler wakeup

TSchedulerWakeup = function(CPUID:LongWord):LongWord;

Scheduler expire

TSchedulerExpire = function(CPUID:LongWord):LongWord;

Scheduler switch

TSchedulerSwitch = function(CPUID:LongWord; Thread:TThreadHandle):TThreadHandle;

Scheduler select

TSchedulerSelect = function(CPUID:LongWord; Thread:TThreadHandle; Yield:Boolean):TThreadHandle;

Scheduler reschedule

TSchedulerReschedule = function (Yield:Boolean):LongWord;

Scheduler migration enable

TSchedulerMigrationEnable = function:LongWord;

Scheduler migration disable

TSchedulerMigrationDisable = function:LongWord;

Scheduler preempt enable

TSchedulerPreemptEnable = function(CPUID:LongWord):LongWord;

Scheduler preempt disable

TSchedulerPreemptDisable = function(CPUID:LongWord):LongWord;

Scheduler allocation enable

TSchedulerAllocationEnable = function(CPUID:LongWord):LongWord;

Scheduler allocation disable

TSchedulerAllocationDisable = function(CPUID:LongWord):LongWord;

Thread setup stack

TThreadSetupStack = function(StackBase:Pointer; StartProc:TThreadStart; ReturnProc:TThreadEnd; Parameter:Pointer):Pointer;


Public variables



Thread logging

THREAD_DEFAULT_LOG_LEVEL:LongWord = THREAD_LOG_LEVEL_DEBUG; Minimum level for Thread messages. Only messages with level greater than or equal to this will be printed.
THREAD_LOG_ENABLED:Boolean;

Scheduler variables

SchedulerThreadNext:LongWord; The CPU to assign the next created thread to, round robin incremented on each create (Protected by ThreadTableLock)
SchedulerThreadMigration:LongWord; Enable or Disable thread migration (SCHEDULER_MIGRATION_DISABLED or SCHEDULER_MIGRATION_ENABLED
SchedulerMigrationQuantum:LongWord; Quantum for thread migration checks (CPU 0 only)
SchedulerThreadCount:array of LongWord; Current number of ready threads per CPU (One per CPU, allocated by scheduler initialization) (Protected by InterlockedIncrement/Decrement)
SchedulerThreadQuantum:array of LongWord; Quantum of current thread per CPU (One per CPU, allocated by scheduler initialization)
SchedulerThreadPreempt:array of LongWord; Current state of thread preemption per CPU (eg SCHEDULER_PREEMPT_DISABLED) (One per CPU, allocated by scheduler initialization)
SchedulerThreadAllocation:array of LongWord; Current state of thread allocation per CPU (eg SCHEDULER_ALLOCATION_DISABLED) (One per CPU, allocated by scheduler initialization)
SchedulerPriorityMask:array of LongWord; Mask of ready threads at each priority level (One per CPU, allocated by scheduler initialization) (Protected by InterlockedOr/And)
SchedulerYieldCurrent:array of LongBool; Scheduler yield to current priority level status (One per CPU, allocated by scheduler initialization)
SchedulerStarvationNext:array of LongWord; Scheduler starvation priority round robin (One per CPU, allocated by scheduler initialization)
SchedulerStarvationQuantum:array of LongWord; Quantum for thread starvation checks per CPU (One per CPU, allocated by scheduler initialization)
SchedulerNoneQueue:array of TQueueHandle; Queue of threads that are ready to run at priority level none (One per CPU, allocated by scheduler initialization)
SchedulerIdleQueue:array of TQueueHandle; Queue of threads that are ready to run at priority level idle (One per CPU, allocated by scheduler initialization)
SchedulerLowestQueue:array of TQueueHandle; Queue of threads that are ready to run at priority level lowest (One per CPU, allocated by scheduler initialization)
SchedulerLowerQueue:array of TQueueHandle; Queue of threads that are ready to run at priority level lower (One per CPU, allocated by scheduler initialization)
SchedulerNormalQueue:array of TQueueHandle; Queue of threads that are ready to run at priority level normal (One per CPU, allocated by scheduler initialization)
SchedulerHigherQueue:array of TQueueHandle; Queue of threads that are ready to run at priority level higher (One per CPU, allocated by scheduler initialization)
SchedulerHighestQueue:array of TQueueHandle; Queue of threads that are ready to run at priority level highest (One per CPU, allocated by scheduler initialization)
SchedulerCriticalQueue:array of TQueueHandle; Queue of threads that are ready to run at priority level critical (One per CPU, allocated by scheduler initialization)
SchedulerSleepQueue:array of TQueueHandle; Queue of threads that are currently sleeping (One per CPU, allocated by scheduler initialization)
SchedulerTimeoutQueue:array of TQueueHandle; Queue of threads that are currently waiting with a timeout (One per CPU, allocated by scheduler initialization)
SchedulerTerminationQueue:array of TQueueHandle; Queue of threads that have been terminated (One per CPU, allocated by scheduler initialization)
SchedulerLast:array of LongWord; The timer value of the last scheduler interrupt (One per CPU, allocated by scheduler initialization)
SchedulerInterrupts:array of LongWord; Current number of scheduler interrupts per CPU (When this reaches SCHEDULER_INTERRUPTS_PER_SECOND then UtilizationLast is updated and UtilizationCurrent is reset) (One per CPU, allocated by scheduler initialization)

Heap manager variables

HeapLock:THeapLock;

RTL thread manager variables

ThreadVarBlockSize:DWORD;

Inititalization handlers

PrimaryInitHandler:TPrimaryInit;
SchedulerInitHandler:TSchedulerInit;
SchedulerStartHandler:TSchedulerStart;
SecondaryInitHandler:TSecondaryInit;
SecondaryBootHandler:TSecondaryBoot;

SpinLock/Unlock handlers

SpinLockHandler:TSpinLock;
SpinUnlockHandler:TSpinUnlock;
SpinLockIRQHandler:TSpinLockIRQ;
SpinUnlockIRQHandler:TSpinUnlockIRQ;
SpinLockFIQHandler:TSpinLockFIQ;
SpinUnlockFIQHandler:TSpinUnlockFIQ;
SpinLockIRQFIQHandler:TSpinLockIRQFIQ;
SpinUnlockIRQFIQHandler:TSpinUnlockIRQFIQ;
SpinCheckIRQHandler:TSpinCheckIRQ;
SpinCheckFIQHandler:TSpinCheckFIQ;
SpinExchangeIRQHandler:TSpinExchangeIRQ;
SpinExchangeFIQHandler:TSpinExchangeFIQ;
SpinMaskExchangeHandler:TSpinMaskExchange;

MutexLock/Unlock handlers

MutexLockHandler:TMutexLock;
MutexUnlockHandler:TMutexUnlock;
MutexTryLockHandler:TMutexTryLock;

CriticalSection Lock/Unlock/TryLock handlers

CriticalSectionLockHandler:TCriticalSectionLock;
CriticalSectionLockExHandler:TCriticalSectionLockEx;
CriticalSectionUnlockHandler:TCriticalSectionUnlock;
CriticalSectionTryLockHandler:TCriticalSectionTryLock;

Semaphore Wait/Signal handlers

SemaphoreWaitHandler:TSemaphoreWait;
SemaphoreWaitExHandler:TSemaphoreWaitEx;
SemaphoreSignalHandler:TSemaphoreSignal;

Synchronizer Reader/WriterLock/Unlock handlers

SynchronizerReaderLockHandler:TSynchronizerLock;
SynchronizerWriterLockHandler:TSynchronizerLock;
SynchronizerReaderLockExHandler:TSynchronizerLockEx;
SynchronizerWriterLockExHandler:TSynchronizerLockEx;
SynchronizerReaderUnlockHandler:TSynchronizerUnlock;
SynchronizerWriterUnlockHandler:TSynchronizerUnlock;
SynchronizerReaderConvertHandler:TSynchronizerConvert;
SynchronizerWriterConvertHandler:TSynchronizerConvert;
SynchronizerReaderConvertExHandler:TSynchronizerConvertEx;

Messageslot send and receive handlers

MessageslotSendHandler:TMessageslotSend;
MessageslotReceiveHandler:TMessageslotReceive;
MessageslotReceiveExHandler:TMessageslotReceiveEx;

Mailslot send and receive handlers

MailslotSendHandler:TMailslotSend;
MailslotSendExHandler:TMailslotSendEx;
MailslotReceiveHandler:TMailslotReceive;
MailslotReceiveExHandler:TMailslotReceiveEx;

Buffer Get/GetEx/Free handlers

BufferGetHandler:TBufferGet;
BufferGetExHandler:TBufferGetEx;
BufferFreeHandler:TBufferFree;
BufferIterateHandler:TBufferIterate;

Event Wait/Set/Reset/Pulse handlers

EventWaitHandler:TEventWait;
EventWaitExHandler:TEventWaitEx;
EventSetHandler:TEventSet;
EventResetHandler:TEventReset;
EventPulseHandler:TEventPulse;

Timer Enable/Disable/Check/Trigger handlers

TimerEnableHandler:TTimerEnable;
TimerEnableExHandler:TTimerEnableEx;
TimerDisableHandler:TTimerDisable;
TimerCheckHandler:TTimerCheck;
TimerTriggerHandler:TTimerTrigger;

Tasker Check/Trigger handlers

TaskerCheckHandler:TTaskerCheck;
TaskerTriggerHandler:TTaskerTrigger;

Thread Get/SetCurrent handlers

ThreadGetCurrentHandler:TThreadGetCurrent;
ThreadSetCurrentHandler:TThreadSetCurrent;

Scheduler Check/Wakeup/Expire/Select/Switch handlers

SchedulerCheckHandler:TSchedulerCheck;
SchedulerWakeupHandler:TSchedulerWakeup;
SchedulerExpireHandler:TSchedulerExpire;
SchedulerSwitchHandler:TSchedulerSwitch;
SchedulerSelectHandler:TSchedulerSelect;
SchedulerRescheduleHandler:TSchedulerReschedule;
SchedulerMigrationEnableHandler:TSchedulerMigrationEnable;
SchedulerMigrationDisableHandler:TSchedulerMigrationDisable;
SchedulerPreemptEnableHandler:TSchedulerPreemptEnable;
SchedulerPreemptDisableHandler:TSchedulerPreemptDisable;
SchedulerAllocationEnableHandler:TSchedulerAllocationEnable;
SchedulerAllocationDisableHandler:TSchedulerAllocationDisable;

Thread SetupStack handlers

ThreadSetupStackHandler:TThreadSetupStack;


Function declarations



Initialization functions

procedure LocksInit;
Description: Initialize Locks
Note None documented


procedure ThreadsInit;
Description: Initialize Threading
Note None documented


procedure PrimaryInit;
Description: Initialize the primary CPU
Note None documented


procedure SchedulerInit;
Description: Initialize the thread scheduler
Note None documented


procedure SchedulerStart(CPUID:LongWord);
Description: Initialize the thread scheduler for secondary CPUs (Where Applicable)
Note None documented


procedure SecondaryInit;
Description: Initialize the secondary CPUs (Where Applicable)
Note None documented


procedure SecondaryBoot(CPUID:LongWord);
Description: Boot the specified secondary CPU (Where Applicable)
Note None documented


procedure SecondaryStart(CPUID:LongWord);
Description: Startup procedure for secondary CPUs (Where Applicable)
Note The Secondary Boot procedure should have already cleared L1 cache, enabled FPU, MMU, Vectors and PageTables before calling this function. The thread Id of the IRQ or FIQ should also have been loaded into the appropriate registers.


function IRQExecute(Parameter:Pointer):PtrInt;
Description: To be documented
Note None documented


function FIQExecute(Parameter:Pointer):PtrInt;
Description: To be documented
Note None documented


function SWIExecute(Parameter:Pointer):PtrInt;
Description: To be documented
Note None documented


function IdleExecute(Parameter:Pointer):PtrInt;
Description: To be documented
Note None documented


function MainExecute(Parameter:Pointer):PtrInt;
Description: To be documented
Note None documented


function TimerExecute(Parameter:Pointer):PtrInt;
Description: To be documented
Note None documented


function WorkerExecute(Parameter:Pointer):PtrInt;
Description: To be documented
Note None documented


function TimerPriorityExecute(Parameter:Pointer):PtrInt;
Description: To be documented
Note None documented


function WorkerPriorityExecute(Parameter:Pointer):PtrInt;
Description: To be documented
Note None documented


function IdleCalibrate:LongWord;
Description: Calibrate the idle thread loop by counting the number of loops in 100ms
Note None documented


Spin functions

function SpinCreate:TSpinHandle; {$IFDEF SPIN_INLINE}inline; {$ENDIF}
Description: Create and insert a new Spin entry
Return Handle of new Spin entry or INVALID_HANDLE_VALUE if entry could not be created


function SpinCreateEx(InitialOwner:Boolean):TSpinHandle;
Description: Create and insert a new Spin entry
InitialOwner If true set the state of the spin to locked and the owner to the current thread
Return Handle of new Spin entry or INVALID_HANDLE_VALUE if entry could not be created


function SpinDestroy(Spin:TSpinHandle):LongWord;
Description: Destroy and remove an existing Spin entry
Spin Handle of Spin entry to destroy
Return ERROR_SUCCESS if completed or another error code on failure


function SpinOwner(Spin:TSpinHandle):TThreadHandle;
Description: Get the current owner of an existing Spin entry
Spin Handle of Spin entry to get owner for
Return Handle of owning thread or INVALID_HANDLE_VALUE if not currently owned


function SpinLock(Spin:TSpinHandle):LongWord; {$IFDEF SPIN_INLINE}inline; {$ENDIF}
Description: Lock an existing Spin entry
Spin Handle of Spin entry to lock
Return ERROR_SUCCESS if completed or another error code on failure


function SpinUnlock(Spin:TSpinHandle):LongWord; {$IFDEF SPIN_INLINE}inline; {$ENDIF}
Description: Unlock an existing Spin entry
Spin Handle of Spin entry to unlock
Return ERROR_SUCCESS if completed or another error code on failure


function SpinLockIRQ(Spin:TSpinHandle):LongWord; {$IFDEF SPIN_INLINE}inline; {$ENDIF}
Description: Lock an existing Spin entry, disable IRQ and save the previous IRQ state
Spin Handle of Spin entry to lock
Return ERROR_SUCCESS if completed or another error code on failure


function SpinUnlockIRQ(Spin:TSpinHandle):LongWord; {$IFDEF SPIN_INLINE}inline; {$ENDIF}
Description: Unlock an existing Spin entry and restore the previous IRQ state
Spin Handle of Spin entry to unlock
Return ERROR_SUCCESS if completed or another error code on failure


function SpinLockFIQ(Spin:TSpinHandle):LongWord; {$IFDEF SPIN_INLINE}inline; {$ENDIF}
Description: Lock an existing Spin entry, disable FIQ and save the previous FIQ state
Spin Handle of Spin entry to lock
Return ERROR_SUCCESS if completed or another error code on failure


function SpinUnlockFIQ(Spin:TSpinHandle):LongWord; {$IFDEF SPIN_INLINE}inline; {$ENDIF}
Description: Unlock an existing Spin entry and restore the previous FIQ state
Spin Handle of Spin entry to unlock
Return ERROR_SUCCESS if completed or another error code on failure


function SpinLockIRQFIQ(Spin:TSpinHandle):LongWord; {$IFDEF SPIN_INLINE}inline; {$ENDIF}
Description: Lock an existing Spin entry, disable IRQ and FIQ and save the previous IRQ and FIQ state
Spin Handle of Spin entry to lock
Return ERROR_SUCCESS if completed or another error code on failure


function SpinUnlockIRQFIQ(Spin:TSpinHandle):LongWord; {$IFDEF SPIN_INLINE}inline; {$ENDIF}
Description: Unlock an existing Spin entry and restore the previous IRQ and FIQ state
Spin Handle of Spin entry to unlock
Return ERROR_SUCCESS if completed or another error code on failure


function SpinCheckIRQ(Spin:TSpinHandle):Boolean;
Description: Check the mask that stores the previous IRQ state to determine if IRQ is enabled
Spin Handle of Spin entry to check
Return True if the mask would enable IRQ on restore, False if it would not
Note The Spin entry must be locked by the current thread


function SpinCheckFIQ(Spin:TSpinHandle):Boolean;
Description: Check the mask that stores the previous FIQ state to determine if FIQ is enabled
Spin Handle of Spin entry to check
Return True if the mask would enable FIQ on restore, False if it would not
Note The Spin entry must be locked by the current thread


function SpinExchangeIRQ(Spin1,Spin2:TSpinHandle):LongWord;
Description: Exchange the previous IRQ state between two Spin entries
Spin1 Handle of first Spin entry
Spin2 Handle of second Spin entry
Return ERROR_SUCCESS if completed or another error code on failure
Note Both Spin entries must be locked by the current thread


function SpinExchangeFIQ(Spin1,Spin2:TSpinHandle):LongWord;
Description: Exchange the previous FIQ state between two Spin entries
Spin1 Handle of first Spin entry
Spin2 Handle of second Spin entry
Return ERROR_SUCCESS if completed or another error code on failure
Note Both Spin entries must be locked by the current thread


function SpinLockDefault(SpinEntry:PSpinEntry):LongWord;
Description: Default version of SpinLock function used if no handler is registered
Note Not intended to be called directly by applications, use SpinLock instead


function SpinUnlockDefault(SpinEntry:PSpinEntry):LongWord;
Description: Default version of SpinUnlock function used if no handler is registered
Note Not intended to be called directly by applications, use SpinUnlock instead


function SpinLockIRQDefault(SpinEntry:PSpinEntry):LongWord;
Description: Default version of SpinLockIRQ function used if no handler is registered
Note Not intended to be called directly by applications, use SpinLockIRQ instead


function SpinUnlockIRQDefault(SpinEntry:PSpinEntry):LongWord;
Description: Default version of SpinUnlockIRQ function used if no handler is registered
Note Not intended to be called directly by applications, use SpinUnlockIRQ instead


function SpinLockFIQDefault(SpinEntry:PSpinEntry):LongWord;
Description: Default version of SpinLockFIQ function used if no handler is registered
Note Not intended to be called directly by applications, use SpinLockFIQ instead


function SpinUnlockFIQDefault(SpinEntry:PSpinEntry):LongWord;
Description: Default version of SpinUnlockFIQ function used if no handler is registered
Note Not intended to be called directly by applications, use SpinUnlockFIQ instead


function SpinLockIRQFIQDefault(SpinEntry:PSpinEntry):LongWord;
Description: Default version of SpinLockIRQFIQ function used if no handler is registered
Note Not intended to be called directly by applications, use SpinLockIRQFIQ instead


Mutex functions

function MutexCreate:TMutexHandle; {$IFDEF MUTEX_INLINE}inline; {$ENDIF}
Description: Create and insert a new Mutex entry
Return Handle of new Mutex entry or INVALID_HANDLE_VALUE if entry could not be created


function MutexCreateEx(InitialOwner:Boolean; SpinCount:LongWord; Flags:LongWord):TMutexHandle;
Description: Create and insert a new Mutex entry
InitialOwner If true set the state of the mutex to locked and the owner to the current thread
SpinCount The number of times the mutex will spin before yielding (Always 0 if CPU count equals 1)
Flags The flags for the Mutex entry (eg MUTEX_FLAG_RECURSIVE)
Return Handle of new Mutex entry or INVALID_HANDLE_VALUE if entry could not be created


function MutexDestroy(Mutex:TMutexHandle):LongWord;
Description: Destroy and remove an existing Mutex entry
Mutex Handle of Mutex entry to destroy
Return ERROR_SUCCESS if completed or another error code on failure


function MutexFlags(Mutex:TMutexHandle):LongWord;
Description: Get the current flags of an existing Mutex entry
Mutex Handle of Mutex entry to get flags for
Return Current flags or INVALID_HANDLE_VALUE on error


function MutexCount(Mutex:TMutexHandle):LongWord;
Description: Get the current lock count of an existing Mutex entry
Mutex Mutex to get count for
Return Current lock count or INVALID_HANDLE_VALUE on error
Note Count is only valid if Flags includes MUTEX_FLAG_RECURSIVE


function MutexOwner(Mutex:TMutexHandle):TThreadHandle;
Description: Get the current owner of an existing Mutex entry
Mutex Handle of Mutex entry to get owner for
Return Handle of owning thread or INVALID_HANDLE_VALUE if not currently owned


function MutexLock(Mutex:TMutexHandle):LongWord; {$IFDEF MUTEX_INLINE}inline; {$ENDIF}
Description: Lock an existing Mutex entry
Mutex Handle of Mutex entry to lock
Return ERROR_SUCCESS if completed or another error code on failure


function MutexUnlock(Mutex:TMutexHandle):LongWord; {$IFDEF MUTEX_INLINE}inline; {$ENDIF}
Description: Unlock an existing Mutex entry
Mutex Handle of Mutex entry to unlock
Return ERROR_SUCCESS if completed or another error code on failure


function MutexTryLock(Mutex:TMutexHandle):LongWord; {$IFDEF MUTEX_INLINE}inline; {$ENDIF}
Description: Try to lock an existing Mutex entry. If the Mutex is not locked then lock it and mark the owner as the current thread. If the Mutex is already locked then return immediately with an error and do not wait for it to be unlocked.
Mutex Mutex to try to lock
Return ERROR_SUCCESS if completed, ERROR_LOCKED if already locked or another error code on failure


function MutexLockDefault(MutexEntry:PMutexEntry):LongWord;
Description: Default version of MutexLock function used if no handler is registered
Note Not intended to be called directly by applications, use MutexLock instead


function MutexUnlockDefault(MutexEntry:PMutexEntry):LongWord;
Description: Default version of MutexUnlock function used if no handler is registered
Note Not intended to be called directly by applications, use MutexUnlock instead


function MutexTryLockDefault(MutexEntry:PMutexEntry):LongWord;
Description: Default version of MutexTryLock function used if no handler is registered
Note Not intended to be called directly by applications, use MutexTryLock instead


Critical section functions

function CriticalSectionCreate:TCriticalSectionHandle;
Description: Create and insert a new CriticalSection entry
Return Handle of new CriticalSection entry or INVALID_HANDLE_VALUE if entry could not be created


function CriticalSectionCreateEx(InitialOwner:Boolean; SpinCount:LongWord):TCriticalSectionHandle;
Description: Create and insert a new CriticalSection entry
CriticalSection If true set the state of the criticalsection to locked and the owner to the current thread
SpinCount The number of times the criticalsection will spin before waiting (Always 0 if CPU count equals 1)
Return Handle of new CriticalSection entry or INVALID_HANDLE_VALUE if entry could not be created


function CriticalSectionDestroy(CriticalSection:TCriticalSectionHandle):LongWord;
Description: Destroy and remove an existing CriticalSection entry
CriticalSection Handle of CriticalSection entry to destroy
Return ERROR_SUCCESS if completed or another error code on failure


function CriticalSectionCount(CriticalSection:TCriticalSectionHandle):LongWord;
Description: Get the current lock count of an existing CriticalSection entry
CriticalSection CriticalSection to get count for
Return Current lock count or INVALID_HANDLE_VALUE on error


function CriticalSectionOwner(CriticalSection:TCriticalSectionHandle):TThreadHandle;
Description: Get the current owner of an existing CriticalSection entry
CriticalSection CriticalSection to get owner for
Return Handle of owning thread or INVALID_HANDLE_VALUE if not currently owned


function CriticalSectionSetSpinCount(CriticalSection:TCriticalSectionHandle; SpinCount:LongWord):LongWord;
Description: Set the spin count of an existing CriticalSection entry
CriticalSection CriticalSection to set spin count for
SpinCount The spin count value to set
Return Current spin count or INVALID_HANDLE_VALUE on error


function CriticalSectionLock(CriticalSection:TCriticalSectionHandle):LongWord;
Description: Lock an existing CriticalSection entry
CriticalSection CriticalSection to lock
Return ERROR_SUCCESS if completed or another error code on failure
Note If the CriticalSection is not locked then lock it, set the count to one and mark the owner as the current thread. If the CriticalSection is already locked by the current thread then increment the count and return immediately. If the CriticalSection is already locked by another thread then wait until it is unlocked.


function CriticalSectionLockEx(CriticalSection:TCriticalSectionHandle; Timeout:LongWord):LongWord;
Description: Lock an existing CriticalSection entry
CriticalSection CriticalSection to lock
Timeout Milliseconds to wait before timeout (0 equals do not wait, INFINITE equals wait forever)
Return ERROR_SUCCESS if completed or another error code on failure
Note If the CriticalSection is not locked then lock it, set the count to one and mark the owner as the current thread. If the CriticalSection is already locked by the current thread then increment the count and return immediately. If the CriticalSection is already locked by another thread then wait until it is unlocked.


function CriticalSectionUnlock(CriticalSection:TCriticalSectionHandle):LongWord;
Description: Unlock an existing CriticalSection entry
CriticalSection CriticalSection to unlock
Return ERROR_SUCCESS if completed or another error code on failure
Note If the CriticalSection is locked by the current thread then decrement the count. If the count is greater than zero then return immediately. If the count reaches zero then unlock the CriticalSection and release the first thread waiting for it to be unlocked. If the CriticalSection is locked by another thread then return an error. If the CriticalSection is not locked then return an error.


function CriticalSectionTryLock(CriticalSection:TCriticalSectionHandle):LongWord;
Description: Try to lock an existing CriticalSection entry
CriticalSection CriticalSection to try to lock
Return ERROR_SUCCESS if completed, ERROR_LOCKED if locked by another thread or another error code on failure
Note If the CriticalSection is not locked then lock it, set the count to one and mark the owner as the current thread. If the CriticalSection is already locked by the current thread then increment the count and return immediately. If the CriticalSection is already locked by another thread then return immediately with an error and do not wait for it to be unlocked.


Semaphore functions

function SemaphoreCreate(Count:LongWord):TSemaphoreHandle;
Description: Create and insert a new Semaphore entry
Count The initial count of the Semaphore (Must be greater than or equal to zero)
Return Handle of new Semaphore entry or INVALID_HANDLE_VALUE if entry could not be created


function SemaphoreCreateEx(Count,Maximum:LongWord; Flags:LongWord):TSemaphoreHandle;
Description: Create and insert a new Semaphore entry
Count The initial count of the Semaphore (Must be greater than or equal to zero)
Maximum The maximum count of the Semaphore (Must be greater than one)
Flags The flags for the Semaphore entry (eg SEMAPHORE_FLAG_IRQ)
Return Handle of new Semaphore entry or INVALID_HANDLE_VALUE if entry could not be created


function SemaphoreDestroy(Semaphore:TSemaphoreHandle):LongWord;
Description: Destroy and remove an existing Semaphore entry
Semaphore Handle of Semaphore entry to destroy
Return ERROR_SUCCESS if completed or another error code on failure


function SemaphoreCount(Semaphore:TSemaphoreHandle):LongWord;
Description: Get the current count of an existing Semaphore entry
Semaphore Semaphore to get count for
Return Current count or INVALID_HANDLE_VALUE on error


function SemaphoreWait(Semaphore:TSemaphoreHandle):LongWord;
Description: Wait on an existing Semaphore entry
Semaphore Semaphore to wait on
Return ERROR_SUCCESS if completed or another error code on failure
Note If the Semaphore count is greater than zero it will be decremented and this function will return immediately. If the Semaphore count is zero the current thread will be put on a wait queue until the Semaphore is signalled by another thread calling SemaphoreSignal() or SemaphoreSignalEx().


function SemaphoreWaitEx(Semaphore:TSemaphoreHandle; Timeout:LongWord):LongWord;
Description: Wait on an existing Semaphore entry
Semaphore Semaphore to wait on
Timeout Milliseconds to wait before timeout (0 equals do not wait, INFINITE equals wait forever)
Return ERROR_SUCCESS if completed or another error code on failure
Note If the Semaphore count is greater than zero it will be decremented and this function will return immediately. If the Semaphore count is zero the current thread will be put on a wait queue until the Semaphore is signalled by another thread calling SemaphoreSignal() or SemaphoreSignalEx().


function SemaphoreSignal(Semaphore:TSemaphoreHandle):LongWord;
Description: Signal an existing Semaphore entry
Semaphore Semaphore to signal
Return ERROR_SUCCESS if completed or another error code on failure
Note If any threads are waiting on the Semaphore then one thread will be woken up and placed on the ready queue. If no threads are wait then the Semaphore count will be incremented.


function SemaphoreSignalEx(Semaphore:TSemaphoreHandle; Count:LongWord; Previous:PLongWord):LongWord;
Description: Signal an existing Semaphore entry one or more times
Semaphore Semaphore to signal
Count The number is times to signal the Semaphore, must be greater than zero
Previous A pointer to a value that receives the previous count of the Semaphore. Can be nil if the previous count is not required
Return ERROR_SUCCESS if completed or another error code on failure
Note If any threads are waiting on the Semaphore then one thread will be woken up and placed on the ready queue for each interation of the count passed. If no threads are wait then the Semaphore count will be incremented once for each interation of the count passed.


Synchronizer functions

function SynchronizerCreate:TSynchronizerHandle;
Description: Create and insert a new Synchronizer entry
Return Handle of new Synchronizer entry or INVALID_HANDLE_VALUE if entry could not be created


function SynchronizerCreateEx(InitialReader,InitialWriter:Boolean):TSynchronizerHandle;
Description: Create and insert a new Synchronizer entry
InitialReader If true set the state of the synchronizer to locked and the reader count to 1
InitialWriter If true set the state of the synchronizer to locked and the writer owner to the current thread
Return Handle of new Synchronizer entry or INVALID_HANDLE_VALUE if entry could not be created


function SynchronizerDestroy(Synchronizer:TSynchronizerHandle):LongWord;
Description: Destroy and remove an existing Synchronizer entry
Synchronizer Handle of Synchronizer entry to destroy
Return ERROR_SUCCESS if completed or another error code on failure


function SynchronizerReaderCount(Synchronizer:TSynchronizerHandle):LongWord;
Description: Get the current reader count of an existing Synchronizer entry
Synchronizer Synchronizer to get count for
Return Current reader count or INVALID_HANDLE_VALUE on error


function SynchronizerReaderLast(Synchronizer:TSynchronizerHandle):TThreadHandle;
Description: Get the last reader thread of an existing Synchronizer entry
Synchronizer Synchronizer to last reader for
Return Last reader thread or INVALID_HANDLE_VALUE on error


function SynchronizerReaderLock(Synchronizer:TSynchronizerHandle):LongWord;
Description: Lock an existing Synchronizer entry for reading
Synchronizer Synchronizer to lock
Return ERROR_SUCCESS if completed or another error code on failure
Note If the Synchronizer is not locked then lock it and set the reader count to one. If the Synchronizer is already locked for reading then increment the reader count and return immediately. If the Synchronizer is already locked for writing then wait until it is unlocked.


function SynchronizerReaderLockEx(Synchronizer:TSynchronizerHandle; Timeout:LongWord):LongWord;
Description: Lock an existing Synchronizer entry for reading
Synchronizer Synchronizer to lock
Timeout Milliseconds to wait before timeout (0 equals do not wait, INFINITE equals wait forever)
Return ERROR_SUCCESS if completed or another error code on failure
Note If the Synchronizer is not locked then lock it and set the reader count to one. If the Synchronizer is already locked for reading then increment the reader count and return immediately. If the Synchronizer is already locked for writing then wait until it is unlocked.


function SynchronizerReaderUnlock(Synchronizer:TSynchronizerHandle):LongWord;
Description: Unlock an existing Synchronizer entry
Synchronizer Synchronizer to unlock
Return ERROR_SUCCESS if completed or another error code on failure
Note If the Synchronizer is locked for reading then decrement the count. If the count is greater than zero then return immediately. If the count reaches zero then unlock the Synchronizer and release the first writer thread waiting for it to be unlocked. If the Synchronizer is locked for writing then return an error. If the Synchronizer is not locked then return an error.


function SynchronizerReaderConvert(Synchronizer:TSynchronizerHandle):LongWord;
Description: Convert a reader lock on an existing Synchronizer entry to a writer lock
Synchronizer Synchronizer to convert
Return ERROR_SUCCESS if completed or another error code on failure
Note If the Synchronizer is locked for reading then decrement the count. If the count is greater than zero then wait to acquire the writer lock. If the count reaches zero then convert to writer lock with the current thread as the owner. If the Synchronizer is locked for writing then return an error. If the Synchronizer is not locked then return an error. Since reader locks are recursive but do not maintain reader thread ownership, caller must ensure that one and only one reader lock is held by the current thread.


function SynchronizerReaderConvertEx(Synchronizer:TSynchronizerHandle; Timeout:LongWord):LongWord;
Description: Convert a reader lock on an existing Synchronizer entry to a writer lock
Synchronizer Synchronizer to convert
Timeout Milliseconds to wait before timeout (0 equals do not wait, INFINITE equals wait forever)
Return ERROR_SUCCESS if completed or another error code on failure
Note If the Synchronizer is locked for reading then decrement the count. If the count is greater than zero then wait to acquire the writer lock. If the count reaches zero then convert to writer lock with the current thread as the owner. If the Synchronizer is locked for writing then return an error. If the Synchronizer is not locked then return an error. Since reader locks are recursive but do not maintain reader thread ownership, caller must ensure that one and only one reader lock is held by the current thread.


function SynchronizerWriterCount(Synchronizer:TSynchronizerHandle):LongWord;
Description: Get the current writer count of an existing Synchronizer entry
Synchronizer Synchronizer to get count for
Return Current writer count or INVALID_HANDLE_VALUE on error


function SynchronizerWriterOwner(Synchronizer:TSynchronizerHandle):TThreadHandle;
Description: Get the current writer owner of an existing Synchronizer entry
Synchronizer Synchronizer to get owner for
Return Handle of owning thread or INVALID_HANDLE_VALUE if not currently owned


function SynchronizerWriterLock(Synchronizer:TSynchronizerHandle):LongWord;
Description: Lock an existing Synchronizer entry for writing
Synchronizer Synchronizer to lock
Return ERROR_SUCCESS if completed or another error code on failure
Note If the Synchronizer is not locked then lock it, set the writer count to one and mark the owner as the current thread. If the Synchronizer is already locked by the current thread then increment the writer count and return immediately. If the Synchronizer is already locked for reading then wait until it is unlocked.


function SynchronizerWriterLockEx(Synchronizer:TSynchronizerHandle; Timeout:LongWord):LongWord;
Description: Lock an existing Synchronizer entry for writing
Synchronizer Synchronizer to lock
Timeout Milliseconds to wait before timeout (0 equals do not wait, INFINITE equals wait forever)
Return ERROR_SUCCESS if completed or another error code on failure
Note If the Synchronizer is not locked then lock it, set the writer count to one and mark the owner as the current thread. If the Synchronizer is already locked by the current thread then increment the writer count and return immediately. If the Synchronizer is already locked for reading then wait until it is unlocked.


function SynchronizerWriterUnlock(Synchronizer:TSynchronizerHandle):LongWord;
Description: Unlock an existing Synchronizer entry
Synchronizer Synchronizer to unlock
Return ERROR_SUCCESS if completed or another error code on failure
Note If the Synchronizer is locked for writing by the current thread then decrement the count. If the count is greater than zero then return immediately. If the count reaches zero then unlock the Synchronizer and release all reader threads waiting for it to be unlocked or the first writer thread waiting for it to be unlocked. If the Synchronizer is locked for reading then return an error. If the Synchronizer is locked for writing by another thread then return an error. If the Synchronizer is not locked then return an error.


function SynchronizerWriterConvert(Synchronizer:TSynchronizerHandle):LongWord;
Description: Convert a writer lock on an existing Synchronizer entry to a reader lock
Synchronizer Synchronizer to convert
Return ERROR_SUCCESS if completed or another error code on failure
Note If the Synchronizer is locked for writing by the current thread and the count is one then decrement the count. If the count is greater than one then return an error. If the count reaches zero then convert to reader lock and release all waiting reader threads. If the Synchronizer is locked for reading then return an error. If the Synchronizer is not locked then return an error. Since writer locks are recursive, caller must ensure that one and only one writer lock is held by the current thread.


List functions

function ListCreate:TListHandle; {$IFDEF LIST_INLINE}inline; {$ENDIF}
Description: Create and insert a new List entry
Return Handle of new List entry or INVALID_HANDLE_VALUE if entry could not be created


function ListCreateEx(ListType:LongWord; Flags:LongWord):TListHandle;
Description: Create and insert a new List entry
ListType Type of list to create (eg LIST_TYPE_WAIT_SEMAPHORE)
Flags Flags for the new list (eg LIST_FLAG_IRQ)
Return Handle of new List entry or INVALID_HANDLE_VALUE if entry could not be created


function ListDestroy(List:TListHandle):LongWord;
Description: Destroy and remove an existing List entry
List Handle of List entry to destroy
Return ERROR_SUCCESS if completed or another error code on failure
Note If list is part of a synchronisation object then caller must hold the lock on the object containing the list


function ListCount(List:TListHandle):LongWord;
Description: Get the current count from the supplied list
List Handle of List entry to get from
Return List count on success or INVALID_HANDLE_VALUE on failure


function ListAddFirst(List:TListHandle; Element:PListElement):LongWord;
Description: Add the supplied element as the first item in the List
List Handle of List entry to add to
Element The list element to be added
Return ERROR_SUCCESS if completed or another error code on failure
Note If list is part of a synchronisation object then caller must hold the lock on the object containing the list


function ListAddLast(List:TListHandle; Element:PListElement):LongWord;
Description: Add the supplied element as the last item in the List
List Handle of List entry to add to
Element The list element to be added
Return ERROR_SUCCESS if completed or another error code on failure
Note If list is part of a synchronisation object then caller must hold the lock on the object containing the list


function ListGetThread(List:TListHandle; Thread:TThreadHandle):PListElement;
Description: Find the supplied thread in the List and return its element
List Handle of List entry to find from
Thread The thread handle to be found
Return List element on success, nil on failure or list empty
Note If list is part of a synchronisation object then caller must hold the lock on the object containing the list


function ListGetFirst(List:TListHandle):PListElement;
Description: Get the first element from the List
List Handle of List entry to get from
Return List element on success, nil on failure or list empty
Note If list is part of a synchronisation object then caller must hold the lock on the object containing the list


function ListGetFirstEx(List:TListHandle; Remove:Boolean):PListElement;
Description: Get the first element from the List
List Handle of List entry to get from
Remove If true then remove the element from the list
Return List element on success, nil on failure or list empty
Note If list is part of a synchronisation object then caller must hold the lock on the object containing the list


function ListGetLast(List:TListHandle):PListElement;
Description: Get the last element from the List
List Handle of List entry to get from
Return List element on success, nil on failure or list empty
Note If list is part of a synchronisation object then caller must hold the lock on the object containing the list


function ListGetLastEx(List:TListHandle; Remove:Boolean):PListElement;
Description: Get the last element from the List
List Handle of List entry to get from
Remove If true then remove the element from the list
Return List element on success, nil on failure or list empty
Note If list is part of a synchronisation object then caller must hold the lock on the object containing the list


function ListInsert(List:TListHandle; Previous,Element:PListElement):LongWord;
Description: Insert a new element in the List
List Handle of List entry to insert into
Previous The element to insert the new element after
Element The list element to be inserted
Return ERROR_SUCCESS if completed or another error code on failure
Note If list is part of a synchronisation object then caller must hold the lock on the object containing the list


function ListRemove(List:TListHandle; Element:PListElement):LongWord;
Description: Remove an element from the List
List Handle of List entry to remove from
Element The list element to be removed
Return ERROR_SUCCESS if completed or another error code on failure
Note If list is part of a synchronisation object then caller must hold the lock on the object containing the list


function ListIsEmpty(List:TListHandle):Boolean;
Description: Check if the supplied List is empty
List Handle of List entry to check
Return True if List is empty or does not exist, False if List is not empty
Note If list is part of a synchronisation object then caller must hold the lock on the object containing the list


function ListNotEmpty(List:TListHandle):Boolean;
Description: Check if the supplied List is empty
List Handle of List entry to check
Return True if List is not empty, False if List is empty or does not exist
Note If list is part of a synchronisation object then caller must hold the lock on the object containing the list


function ListLock(List:TListHandle):LongWord;
Description: Lock the supplied List
List Handle of List entry to lock
Return ERROR_SUCCESS if completed or another error code on failure


function ListUnlock(List:TListHandle):LongWord;
Description: Unlock the supplied List
List Handle of List entry to unlock
Return ERROR_SUCCESS if completed or another error code on failure


function ListLock(List:TListHandle):LongWord; {$IFDEF LIST_INLINE}inline; {$ENDIF}
Description: Lock the supplied List
List Handle of List entry to lock
Return ERROR_SUCCESS if completed or another error code on failure


function ListUnlock(List:TListHandle):LongWord; {$IFDEF LIST_INLINE}inline; {$ENDIF}
Description: Unlock the supplied List
List Handle of List entry to unlock
Return ERROR_SUCCESS if completed or another error code on failure


Queue functions

function QueueCreate:TQueueHandle; {$IFDEF QUEUE_INLINE}inline; {$ENDIF}
Description: Create and insert a new Queue entry
Return Handle of new Queue entry or INVALID_HANDLE_VALUE if entry could not be created


function QueueCreateEx(QueueType:LongWord; Flags:LongWord):TQueueHandle;
Description: Create and insert a new Queue entry}
'Queue'Type Type of queue to create (eg QUEUE_TYPE_SCHEDULE_SLEEP)
Flags Flags for the new queue (eg QUEUE_FLAG_DESCENDING)
Return Handle of new Queue entry or INVALID_HANDLE_VALUE if entry could not be created


function QueueDestroy(Queue:TQueueHandle):LongWord;
Description: Destroy and remove an existing Queue entry
Queue Handle of Queue entry to destroy
Return ERROR_SUCCESS if completed or another error code on failure


function QueueCount(Queue:TQueueHandle):LongWord;
Description: Get the current count from the supplied queue
List Handle of Queue entry to get from
Return Queue count on success or INVALID_HANDLE_VALUE on failure


function QueueEnqueue(Queue:TQueueHandle; Thread:TThreadHandle):LongWord;
Description: Add the supplied thread as the last item in the Queue
Queue Handle of Queue entry to add to
Thread Handle of the Thread to enqueue
Return ERROR_SUCCESS if completed or another error code on failure
Note If queue is a scheduler queue then caller must hold the lock on the thread


function QueueDequeue(Queue:TQueueHandle):TThreadHandle;
Description: Get and remove the first thread from the Queue
Queue Handle of Queue entry to get from
Return Handle of dequeued Thread or INVALID_HANDLE_VALUE on failure


function QueueFirstKey(Queue:TQueueHandle):Integer;
Description: Get the first Key value from the Queue
Queue Handle of Queue entry to get from
Return First Key value from queue or QUEUE_KEY_NONE on failure


function QueueLastKey(Queue:TQueueHandle):Integer;
Description: Get the last Key value from the Queue
Queue Handle of Queue entry to get from
Return Last Key value from queue or QUEUE_KEY_NONE on failure


function QueueInsertKey(Queue:TQueueHandle; Thread:TThreadHandle; Key:Integer):LongWord;
Description: Insert the supplied thread in the Queue ordered based on Key and the flags of the Queue
Queue Handle of Queue entry to insert into
Thread Handle of thread to be inserted
Key The key to order the insertion on
Return ERROR_SUCCESS if completed or another error code on failure
Note If queue is a scheduler queue then caller must hold the lock on the thread}


function QueueDeleteKey(Queue:TQueueHandle; Thread:TThreadHandle):LongWord;
Description: Delete the supplied thread from the Queue based on the flags of the Queue
Queue Handle of Queue entry to delete from
Thread Handle of thread to be deleted
Return ERROR_SUCCESS if completed or another error code on failure
Note If queue is a scheduler queue then caller must hold the lock on the thread


function QueueIncrementKey(Queue:TQueueHandle):Integer;
Description: Increment the first Key value in the Queue
Queue Handle of Queue entry to increment in
Return First Key value in queue after increment or QUEUE_KEY_NONE on failure


function QueueDecrementKey(Queue:TQueueHandle):Integer;
Description: Decrement the first Key value in the Queue
Queue Handle of Queue entry to decrement in
Return First Key value in queue after decrement or QUEUE_KEY_NONE on failure


function QueueIsEmpty(Queue:TQueueHandle):Boolean;
Description: Check if the supplied Queue is empty
Queue Handle of Queue entry to check
Return True if Queue is empty or does not exist, False if Queue is not empty


function QueueNotEmpty(Queue:TQueueHandle):Boolean;
Description: Check if the supplied Queue is not empty
Queue Handle of Queue entry to check
Return True if Queue is not empty, False if Queue is empty or does not exist


function QueueLock(Queue:TQueueHandle):LongWord; {$IFDEF QUEUE_INLINE}inline; {$ENDIF}
Description: Lock the supplied Queue
Queue Handle of Queue entry to lock
Return ERROR_SUCCESS if completed or another error code on failure


function QueueUnlock(Queue:TQueueHandle):LongWord; {$IFDEF QUEUE_INLINE}inline; {$ENDIF}
Description: Unlock the supplied Queue
Queue Handle of Queue entry to unlock
Return ERROR_SUCCESS if completed or another error code on failure


Thread functions

function ThreadCreate(StartProc:TThreadStart; StackSize,Priority:LongWord; Name:PChar; Parameter:Pointer):TThreadHandle;
Description: Create and insert a new Thread entry
StartProc Procedure address where the thread will start running
StackSize Stack size in bytes
Priority Thread priority (eg THREAD_PRIORITY_NORMAL)
Name To be documented
Parameter Parameter passed to StartProc of new thread
Return Handle of new thread or INVALID_HANDLE_VALUE if a new thread could not be created
Note The new thread will be created suspended so it will not start running until it is scheduled with either ThreadReady or ThreadResume. Calls ThreadCreateEx with: Affinity = SCHEDULER_CPU_MASK (Run on any available CPU) CPU = SchedulerThreadNext (Assign to next CPU in round robin).
Warning ThreadCreate and ThreadCreateEx are only used internally by SysBeginThread and SysBeginThreadEx. These functions do not handle setting up certain RTL functionality such as thread variables, exceptions and standard input/output handles. If you need to create a standard thread use either BeginThread (or BeginThreadEx) or use the TThread class and its descendants. Only use ThreadCreate and ThreadCreateEx if you need to modify the thread creation behaviour and understand that you also need to handle the additional RTL setup.


function ThreadCreateEx(StartProc:TThreadStart; StackSize,Priority,Affinity,CPU:LongWord; Name:PChar; Parameter:Pointer):TThreadHandle;
Description: Create and insert a new Thread entry
StartProc Procedure address where the thread will start running
StackSize Stack size in bytes
Priority Thread priority (eg THREAD_PRIORITY_NORMAL)
Affinity Thread affinity (eg CPU_AFFINITY_ALL)
CPU The CPU to assign new thread to (eg )
Name Name of the thread
Parameter Parameter passed to StartProc of new thread
Return Handle of new thread or INVALID_HANDLE_VALUE if a new thread could not be created
Note The new thread will be created suspended so it will not start running until it is scheduled with either ThreadReady or ThreadResume.
Warning ThreadCreate and ThreadCreateEx are only used internally by SysBeginThread and SysBeginThreadEx. These functions do not handle setting up certain RTL functionality such as thread variables, exceptions and standard input/output handles. If you need to create a standard thread use either BeginThread (or BeginThreadEx) or use the TThread class or its descendants. Only use ThreadCreate and ThreadCreateEx if you need to modify the thread creation behaviour and understand that you also need to handle the additional RTL setup


function ThreadDestroy(Thread:TThreadHandle):LongWord;
Description: Destroy and remove an existing Thread entry
Thread Handle of thread to destroy
Return ERROR_SUCCESS if completed or another error code on failure


function ThreadGetCurrent:TThreadHandle; inline;
Description: Get the Handle of currently executing thread
Return Thread handle of the currently running thread


function ThreadSetCurrent(Thread:TThreadHandle):LongWord; inline;
Description: Set the Handle of currently executing thread
Return ERROR_SUCCESS if completed or another error code on failure
Note Must not be called except during initialization


function ThreadGetName(Thread:TThreadHandle):String;
Description: Get the name of a Thread}
Thread Handle of thread to get
Return Name of thread or empty string on failure


function ThreadSetName(Thread:TThreadHandle; const Name:String):LongWord;
Description: Set the name of a Thread
Thread Handle of thread to set
Return ERROR_SUCCESS if completed or another error code on failure


function ThreadGetCPU(Thread:TThreadHandle):LongWord;
Description: Get the current CPU of a thread (eg CPU_ID_0)
Thread Handle of thread to get
Return CPU of the thread or INVALID_HANDLE_VALUE on failure


function ThreadSetCPU(Thread:TThreadHandle; CPU:LongWord):LongWord;
Description: Set the current CPU of a thread (eg CPU_ID_0)
Thread Handle of thread to set
CPU New thread CPU (eg CPU_ID_0)
Return Previous CPU of thread or INVALID_HANDLE_VALUE on failure
Note The new CPU will not take affect until the thread is next rescheduled


function ThreadGetState(Thread:TThreadHandle):LongWord;
Description: Get the current state of a thread (eg THREAD_STATE_SUSPENDED)
Thread Handle of thread to get
Return State of the thread or INVALID_HANDLE_VALUE on failure


function ThreadGetLocale(Thread:TThreadHandle):LCID;
Description: Get the current locale of a thread
Thread Handle of thread to get
Return Locale of the thread or INVALID_HANDLE_VALUE on failure


function ThreadSetLocale(Thread:TThreadHandle; Locale:LCID):LongWord;
Description: Set the locale of a thread
Thread Handle of thread to set
Locale Locale Id to set
Return ERROR_SUCCESS if completed or another error code on failure


function ThreadGetTimes(Thread:TThreadHandle; var CreateTime,ExitTime,KernelTime:Int64):LongWord;
Description: Get the current times of a thread
Thread Handle of thread to get
CreateTime Buffer to receive the CreateTime value
ExitTime Buffer to receive the ExitTime value
KernelTime Buffer to receive the KernelTime value
Return ERROR_SUCCESS if completed or another error code on failure


function ThreadGetSwitchCount(Thread:TThreadHandle; var SwitchCount:Int64):LongWord;
Description: Get the current context switch count of a thread (How many times the thread has been scheduled)
Thread Handle of thread to get
SwitchCount Buffer to receive the SwitchCount value
Return ERROR_SUCCESS if completed or another error code on failure


function ThreadGetStackFree:LongWord;
Description: Get the free stack size of the current thread
Return Free stack size of the current thread or 0 on error
Note No lock required as only ever called by the thread itself


function ThreadGetStackSize(Thread:TThreadHandle):LongWord;
Description: Get the current stack size of a thread
Thread Handle of thread to get
Return Stack size of the thread or INVALID_HANDLE_VALUE on failure


function ThreadGetStackBase(Thread:TThreadHandle):PtrUInt;
Description: Get the current stack base of a thread
Thread Handle of thread to get
Return Stack base of the thread or INVALID_HANDLE_VALUE on failure


function ThreadSetStackBase(Thread:TThreadHandle; StackBase:PtrUInt):LongWord;
Description: Set the current stack base of a thread
Thread Handle of thread to set
StackBase Stack base to set
Return ERROR_SUCCESS if completed or another error code on failure
Note Must not be called except during initialization


function ThreadGetStackPointer(Thread:TThreadHandle):PtrUInt;
Description: Get the current stack pointer of a thread
Thread Handle of thread to get
Return Stack pointer of the thread or INVALID_HANDLE_VALUE on failure


function ThreadGetExitCode(Thread:TThreadHandle):LongWord;
Description: Get the exit code of a Thread
Thread Handle of thread to get
Return Exit code of thread, STILL_ACTIVE if the thread has not terminated or INVALID_HANDLE_VALUE on failure


function ThreadGetAffinity(Thread:TThreadHandle):LongWord;
Description: Get the scheduling affinity of a Thread
Thread Handle of thread to get
Return Affinity of thread or INVALID_HANDLE_VALUE on failure


function ThreadSetAffinity(Thread:TThreadHandle; Affinity:LongWord):LongWord;
Description: Set the scheduling affinity of a Thread
Thread Handle of thread to set
Affinity New thread affinity (eg CPU_AFFINITY_0)
Return Previous affinity of thread or INVALID_HANDLE_VALUE on failure
Note The new affinity will not take affect until the thread is next rescheduled


function ThreadGetPriority(Thread:TThreadHandle):LongWord;
Description: Get the scheduling priority of a Thread
Thread Handle of thread to get
Return Priority of thread or INVALID_HANDLE_VALUE on failure


function ThreadSetPriority(Thread:TThreadHandle; Priority:LongWord):LongWord;
Description: Set the scheduling priority of a Thread
Thread Handle of thread to set
Priority New thread priority (eg THREAD_PRIORITY_NORMAL)
Return Previous priority of thread or INVALID_HANDLE_VALUE on failure
Note The new priority will not take affect until the thread is next rescheduled


function ThreadGetLastError:LongWord;
Description: Get the last error value for the current Thread
Return Last Error of thread or ERROR_SUCCESS if no error
Note No lock required as only ever called by the thread itself


function ThreadSetLastError(LastError:LongWord):LongWord;
Description: Set the last error value for the current Thread
Return ERROR_SUCCESS if completed or another error code on failure
Note No lock required as only ever called by the thread itself


function ThreadGetWaitResult:LongWord;
Description: Get the result of the last wait timeout for the current Thread
Return Result of last wait timeout or ERROR_SUCCESS if no error
Note No lock required as only ever called by the thread itself


function ThreadGetReceiveResult:LongWord;
Description: Get the result of the last receive timeout for the current Thread
Return Result of last receive timeout or ERROR_SUCCESS if no error
Note No lock required as only ever called by the thread itself


function ThreadAllocTlsIndex:LongWord;
Description: Allocate a TLS index in the TLS index table
Return Allocated TLS index or TLS_OUT_OF_INDEXES on failure


function ThreadAllocTlsIndexEx(Flags:LongWord):LongWord;
Description: Allocate a TLS index in the TLS index table
Flags The flags to apply to the TLS index entries (eg THREAD_TLS_FLAG_FREE)
Return Allocated TLS index or TLS_OUT_OF_INDEXES on failure


function ThreadReleaseTlsIndex(TlsIndex:LongWord):LongWord;
Description: Deallocate a TLS index from the TLS index table
TlsIndex The TLS index to deallocate
Return ERROR_SUCCESS if completed or another error code on failure


function ThreadGetTlsValue(TlsIndex:LongWord):Pointer;
Description: Get the pointer associated with the TLS index for the current thread
Return Pointer for the specified TLS index or nil if not set or on error
Note No lock required as only ever called by the thread itself


function ThreadSetTlsValue(TlsIndex:LongWord; TlsValue:Pointer):LongWord;
Description: Set the pointer associated with the TLS index for the current thread
TlsIndex The TLS index to get the pointer for
Return ERROR_SUCCESS if completed or another error code on failure
Note No lock required as only ever called by the thread itself


function ThreadGetTlsPointer(Thread:TThreadHandle):Pointer;
Description: Get the RTL TLS (Thread Local Storage) pointer of a Thread
Thread Handle of thread to get
Return Pointer to the RTL TLS of thread or nil on failure


function ThreadSetTlsPointer(Thread:TThreadHandle; TlsPointer:Pointer):LongWord;
Description: Set the RTL TLS (Thread Local Storage) pointer of a Thread
Thread Handle of thread to set
TlsPointer Pointer value to set (Can be nil to clear the pointer)
Return ERROR_SUCCESS if completed or another error code on failure


function ThreadReady(Thread:TThreadHandle; Reschedule:Boolean):LongWord;
Description: Place the supplied Thread on the ready queue
Thread Handle of thread to make ready
Reschedule If True then call SchedulerReschedule
Return ERROR_SUCCESS if completed or another error code on failure
Note When called by the scheduler, thread has already been removed from the sleep queue


function ThreadTimeout(Thread:TThreadHandle):LongWord;
Description: Place the supplied Thread on the ready queue after a timeout waiting on a resource
Thread Handle of thread to make ready
Return ERROR_SUCCESS if completed or another error code on failure
Note When called by the scheduler, thread has already been removed from the timeout queue


function ThreadWake(Thread:TThreadHandle):LongWord;
Description: Remove a thread prematurely from the sleep or timeout queues
Thread Handle of thread to remove
Return ERROR_SUCCESS if completed or another error code on failure
Note A thread that was sleeping will simply return early. A thread that was waiting or receiving with a timeout will return with the error WAIT_TIMEOUT. A thread that was waiting or receiving with INFINITE timeout will return with the error WAIT_ABANDONED.


function ThreadMigrate(Thread:TThreadHandle; CPU:LongWord):LongWord;
Description: Migrate a thread to a new CPU
Thread Handle of thread to migrate
CPU New CPU for the thread
Return Previous CPU of thread or INVALID_HANDLE_VALUE on failure


procedure ThreadEnd(ExitCode:LongWord);
Description: Terminate the current Thread
ExitCode The return code of the thread


function ThreadHalt(ExitCode:LongWord):LongWord;
Description: Halt the current thread so it will never be rescheduled
ExitCode The return code of the thread
Return ERROR_SUCCESS if completed or another error code on failure
Note Normally only called due to an unhandled exception etc so that the thread is put to sleep permanently without being terminated


function ThreadTerminate(Thread:TThreadHandle; ExitCode:LongWord):LongWord;
Description: Terminate but do not destroy the supplied Thread
Thread Handle of thread to terminate
ExitCode The return code of the thread
Return ERROR_SUCCESS if completed or another error code on failure
Note The terminated thread is placed on the termination queue until any threads waiting on it have been released


function ThreadYield:LongWord;
Description: Make the current thread yield the processor (Same as ThreadSleep(0))
Return ERROR_SUCCESS if completed or another error code on failure


function ThreadSleep(Milliseconds:LongWord):LongWord;
Description: Place the current thread on the sleep queue for a specified number of milliseconds
Return ERROR_SUCCESS if completed or another error code on failure
Note Milliseconds: Number of milliseconds to sleep


function ThreadWait(List:TListHandle; Lock:TSpinHandle; Flags:LongWord):LongWord;
Description: Put the current thread into a wait state on the supplied list
List Handle of List entry to put thread into
Lock Handle of Lock to release before going into wait state
Flags Flag to indicate which unlock method to use
Return ERROR_SUCCESS if completed or another error code on failure
Note Caller must hold the lock on the synchronisation object containing the list


function ThreadWaitEx(List:TListHandle; Lock:TSpinHandle; Flags,Timeout:LongWord):LongWord;
Description: Put the current thread into a wait state with timeout on the supplied list
List Handle of List entry to put thread into
Lock Handle of Lock to release before going into wait state
Flags Flag to indicate which unlock method to use
Timeout Milliseconds to wait before timeout (INFINITE equals wait forever)
Return ERROR_SUCCESS if completed or another error code on failure
Note Caller must hold the lock on the synchronisation object containing the list


function ThreadRelease(List:TListHandle):LongWord;
Description: Release the first thread waiting on the supplied list
List Handle of List entry to release thread from
Return ERROR_SUCCESS if completed or another error code on failure
Note Caller must hold the lock on the synchronisation object containing the list


function ThreadAbandon(List:TListHandle):LongWord;
Description: Release the first thread waiting on the supplied list and return with WAIT_ABANDONED
List Handle of List entry to release thread from
Return ERROR_SUCCESS if completed or another error code on failure
Note Caller must hold the lock on the synchronisation object containing the list


function ThreadWaitTerminate(Thread:TThreadHandle; Timeout:LongWord):LongWord;
Description: Make the current thread wait until the specified thread has terminated
Thread Handle of the thread to wait on
Timeout Milliseconds to wait before timeout (0 equals do not wait, INFINITE equals wait forever)
Return ERROR_SUCCESS if completed or another error code on failure
Note The wait can be abandoned by calling ThreadWake with the handle of the waiting thread


function ThreadSuspend(Thread:TThreadHandle):LongWord;
Description: Suspend a thread, placing it in hibernation
Thread Handle of thread to suspend
Return ERROR_SUCCESS if completed or another error code on failure
Note Suspending a thread from another thread is not safe unless specific precautions are taken to prevent deadlocks. It is normally safe for a thread to suspend itself as long as it releases any locks it is holding that may be required by other threads before suspending.


function ThreadResume(Thread:TThreadHandle):LongWord;
Description: Resume a suspended thread, making it ready
Thread Handle of thread to resume
Return ERROR_SUCCESS if completed or another error code on failure


function ThreadWaitMessage:LongWord;
Description: Make the current thread wait until a message is received (indefinately)
Return ERROR_SUCCESS if completed or another error code on failure
Note The received message is not removed from the message list


function ThreadSendMessage(Thread:TThreadHandle; const Message:TMessage):LongWord;
Description: Send a message to another thread
Thread Handle of thread to send to
Message Contents of message to send
Return ERROR_SUCCESS if completed or another error code on failure


function ThreadReceiveMessage(var Message:TMessage):LongWord;
Description: Make the current thread wait to receive a message (indefinately)
Message The received message if successful, undefined on error
Return ERROR_SUCCESS if completed or another error code on failure


function ThreadReceiveMessageEx(var Message:TMessage; Timeout:LongWord; Remove:Boolean):LongWord;
Description: Make the current thread wait to receive a message
Message The received message if successful, undefined on error
Timeout Milliseconds to wait before timeout (0 equals do not wait, INFINITE equals wait forever)
Remove If true then remove the received message from the message list
Return ERROR_SUCCESS if completed or another error code on failure


function ThreadAbandonMessage(Thread:TThreadHandle):LongWord;
Description: Tell another thread to abandon waiting for a message
Thread Handle of thread to abandon waiting
Return ERROR_SUCCESS if completed or another error code on failure
Note The waiting thread will return with ERROR_WAIT_ABANDONED or ERROR_WAIT_TIMEOUT


function ThreadLock(Thread:TThreadHandle):LongWord;
Description: Lock a thread allowing access to internal structures such as the thread stack
Thread Handle of thread to lock
Return ERROR_SUCCESS if completed or another error code on failure
Note Locking a thread will also disable IRQ or FIQ depending on scheduler settings. The lock should only be held for the briefest time possible.


function ThreadUnlock(Thread:TThreadHandle):LongWord;
Description: Unlock a thread that was locked by ThreadLock
Thread Handle of thread to unlock
Return ERROR_SUCCESS if completed or another error code on failure
Note Locking a thread will also disable IRQ or FIQ depending on scheduler settings. The lock should only be held for the briefest time possible.


Scheduler functions

function SchedulerCheck(CPUID:LongWord):LongWord;
Description: Check if the sleep queue is empty, if not then decrement the first key. Note: Then check if the timeout queue is empty, if not then decrement the first key. If either key reaches zero, return success to indicate there are threads to be woken or threads whose timeout has expired. Finally check if the termination queue is empty, if not then decrement the first key. Items will be removed from the termination queue by SchedulerReschedule.
CPUID The ID of the current CPU
Return ERROR_SUCCESS if either first key is zero, ERROR_NO_MORE_ITEMS if both queues are empty or another error code on failure
Note Called by scheduler interrupt with IRQ or FIQ disabled and running on the IRQ or FIQ thread


function SchedulerWakeup(CPUID:LongWord):LongWord;
Description: Remove all threads from the sleep queue that have no more time to sleep. Note: Threads will be placed back on the ready queue for rescheduling.
CPUID The ID of the current CPU
Return ERROR_SUCCESS if completed or another error code on failure
Note Called by scheduler interrupt with IRQ or FIQ disabled and running on the IRQ or FIQ thread


function SchedulerExpire(CPUID:LongWord):LongWord;
Description: Remove all threads from the timeout queue that have no more time to wait. Note: Threads will be placed back on the ready queue for rescheduling but will return with an error indicating the timeout expired.
CPUID The ID of the current CPU
Return ERROR_SUCCESS if completed or another error code on failure
Note Called by scheduler interrupt with IRQ or FIQ disabled and running on the IRQ or FIQ thread


function SchedulerSwitch(CPUID:LongWord; Thread:TThreadHandle):TThreadHandle;
Description: Perform a preemptive thread switch operation under an interrupt handler. Note: The next thread to run will be selected based on remaining quantum of the current thread, ready threads at higher priority levels and scheduler priority quantum for fair scheduling of lower priority threads.
CPUID The ID of the current CPU
Thread The handle of the currently running thread (Before IRQ or FIQ occurred)
Return The handle of the current thread which may be the old thread or a new thread
Note Called by scheduler interrupt with IRQ or FIQ disabled and running on the IRQ or FIQ thread


function SchedulerSelect(CPUID:LongWord; Thread:TThreadHandle; Yield:Boolean):TThreadHandle;
Description: Select the next thread to be run based on state, yield, quantum and priority
CPUID The ID of the current CPU
Thread The handle of the currently running thread (Before IRQ or FIQ occurred or when Reschedule was called)
Yield True if the current thread is giving up its remaining time slice
Return The handle of the next thread to run or INVALID_HANDLE_VALUE on no selection or error
Note Called either by scheduler interrupt with IRQ or FIQ disabled and running on the IRQ or FIQ thread. Or by scheduler reschedule with IRQ or FIQ disabled and running on the current thread. Caller must either hold a lock on the current thread or have disabled IRQ or FIQ.


function SchedulerReschedule(Yield:Boolean):LongWord;
Description: Perform a thread switch operation when a thread yields, sleeps or waits. Note: The next thread to run will be selected based on whether the current thread is yielding or no longer ready, remaining quantum of the current thread, ready threads at higher priority levels and scheduler priority quantum for fair scheduling of lower priority threads.
Yield True if the current thread is giving up its remaining time slice
Return ERROR_SUCCESS if completed or another error code on failure
Note Called by the currently running thread to force a reschedule before sleeping, waiting etc


function SchedulerMigrationEnable:LongWord;
Description: Enable scheduler thread migration
Return ERROR_SUCCESS if completed or another error code on failure


function SchedulerMigrationDisable:LongWord;
Description: Disable scheduler thread migration
Return ERROR_SUCCESS if completed or another error code on failure


function SchedulerPreemptEnable(CPUID:LongWord):LongWord;
Description: Enable thread preemption for the specified CPU
CPUID The ID of the CPU to enable for
Return ERROR_SUCCESS if completed or another error code on failure


function SchedulerPreemptDisable(CPUID:LongWord):LongWord;
Description: Disable thread preemption for the specified CPU
CPUID The ID of the CPU to disable for
Return ERROR_SUCCESS if completed or another error code on failure


function SchedulerAllocationEnable(CPUID:LongWord):LongWord;
Description: Enable thread allocation for the specified CPU
CPUID The ID of the CPU to enable for
Return ERROR_SUCCESS if completed or another error code on failure


function SchedulerAllocationDisable(CPUID:LongWord):LongWord;
Description: Disable thread allocation for the specified CPU
CPUID The ID of the CPU to disable for
Return ERROR_SUCCESS if completed or another error code on failure


Messageslot functions

function MessageslotCreate:TMessageslotHandle;
Description: Create and insert a new Messageslot entry
Return Handle of new Messageslot entry or INVALID_HANDLE_VALUE if entry could not be created


function MessageslotCreateEx(Maximum:LongWord; Flags:LongWord):TMessageslotHandle;
Description: Create and insert a new Messageslot entry
Maximum Maximum number of messages allowed for the Messageslot (Must be greater than zero)
Flags The flags for the Messageslot entry (eg MESSAGESLOT_FLAG_IRQ)
Return Handle of new Messageslot entry or INVALID_HANDLE_VALUE if entry could not be created


function MessageslotDestroy(Messageslot:TMessageslotHandle):LongWord;
Description: Destroy and remove an existing Messageslot entry
Messageslot Handle of Messageslot entry to destroy
Return ERROR_SUCCESS if completed or another error code on failure


function MessageslotCount(Messageslot:TMessageslotHandle):LongWord;
Description: Get the number of available messages in a Messageslot entry
Messageslot Messageslot to get from
Return Number of messages or INVALID_HANDLE_VALUE on error


function MessageslotSend(Messageslot:TMessageslotHandle; const Message:TMessage):LongWord;
Description: Send a message to a Messageslot
Messageslot Messageslot to send to
Message Contents of message to send
Return ERROR_SUCCESS if completed or another error code on failure


function MessageslotReceive(Messageslot:TMessageslotHandle; var Message:TMessage):LongWord;
Description: Receive a message from a Messageslot
Messageslot Messageslot to receive from
Message The received message if successful, undefined on error
Return ERROR_SUCCESS if completed or another error code on failure


function MessageslotReceiveEx(Messageslot:TMessageslotHandle; var Message:TMessage; Timeout:LongWord):LongWord;
Description: Receive a message from a Messageslot
Messageslot Messageslot to receive from
Message The received message if successful, undefined on error
Timeout Milliseconds to wait before timeout (0 equals do not wait, INFINITE equals wait forever)
Return ERROR_SUCCESS if completed or another error code on failure


Mailslot functions

function MailslotCreate(Maximum:LongWord):TMailslotHandle;
Description: Create and insert a new Mailslot entry
Maximum Maximum number of messages allowed for the Mailslot (Must be greater than zero)
Return Handle of new Mailslot entry or INVALID_HANDLE_VALUE if entry could not be created


function MailslotDestroy(Mailslot:TMailslotHandle):LongWord;
Description: Destroy and remove an existing Mailslot entry
Mailslot Handle of Mailslot entry to destroy
Return ERROR_SUCCESS if completed or another error code on failure


function MailslotCount(Mailslot:TMailslotHandle):LongWord;
Description: Get the number of available messages in a Mailslot entry
Mailslot Mailslot to get from
Return Number of messages or INVALID_HANDLE_VALUE on error


function MailslotSend(Mailslot:TMailslotHandle; Data:Integer):LongWord;
Description: Send a message to a Mailslot
Mailslot Mailslot to send to
Data Message to send to mailslot
Return ERROR_SUCCESS if completed or another error code on failure


function MailslotSendEx(Mailslot:TMailslotHandle; Data:Integer; Timeout:LongWord):LongWord;
Description: Send a message to a Mailslot
Mailslot Mailslot to send to
Data Message to send to mailslot
Timeout Milliseconds to wait before timeout (0 equals do not wait, INFINITE equals wait forever)
Return ERROR_SUCCESS if completed or another error code on failure


function MailslotReceive(Mailslot:TMailslotHandle):Integer;
Description: Receive a message from a Mailslot
Mailslot Mailslot to receive from
Return Received message or INVALID_HANDLE_VALUE on error


Tasker functions

function TaskerThreadSendMessage(Thread:TThreadHandle; const Message:TMessage):LongWord;
Description: Perform a ThreadSendMessage() function call using the tasker list
Note None documented


function TaskerMessageslotSend(Messageslot:TMessageslotHandle; const Message:TMessage):LongWord;
Description: Perform a MessageslotSend() function call using the tasker list
Note None documented


function TaskerSemaphoreSignal(Semaphore:TSemaphoreHandle; Count:LongWord):LongWord;
Description: Perform a SemaphoreSignal() function call using the tasker list
Note None documented


function TaskerEnqueue(Task:PTaskerTask):LongWord;
Description: Add the supplied task to the end of the Tasker list
Return ERROR_SUCCESS if completed or another error code on failure


function TaskerDequeue:PTaskerTask;
Description: Get and remove the first task from the Tasker list
Return Dequeued Task or nil on failure (or list empty)


function TaskerCheck:LongWord;
Description: Check if the tasker list is empty or contains tasks
Return ERROR_SUCCESS if the list contains tasks, ERROR_NO_MORE_ITEMS if list is empty or another error code on failure
Note Called by clock interrupt with IRQ or FIQ disabled and running on the IRQ or FIQ thread


function TaskerTrigger:LongWord;
Description: Dequeue all tasks in the tasker list and perform the requested task for each
Return ERROR_SUCCESS if completed or another error code on failure
Note Called by clock interrupt with IRQ or FIQ disabled and running on the IRQ or FIQ thread


function TaskerGetCount:LongWord; inline;
Description: Get the current tasker count
Note None documented


Return to Unit Reference