Home

ThreadX User Guide: Green Hills edition

image

Contents

1. When the ISR is finished context is restored or thread preemption by calling the context restore function Control does not return JUMP _ tx thread context restore Some interrupts occur at such a high frequency that saving and restoring full context upon each interrupt would consume excessive processing bandwidth In such cases it is common for the application to have a small assembly language ISR that does a limited amount of processing for a majority of these high frequency interrupts After a certain point in time the small ISR may need to interact with ThreadX This is accomplished by simply calling the entry and exit functions described in the above template ThreadX locks out interrupts over brief periods of time The maximum amount of time interrupts are disabled is on the order of the time required to save or restore a thread s context ELITS d User Guide CHAPTER 4 Description of ThreadX Services This chapter contains a description of all ThreadX services listed below in alphabetic order Their names are designed so that you will find all similar services grouped together For example all memory block services are found at the beginning of this chapter In the Return Values section in the following API descriptions values in BOLD are not affected by the TX DISABLE ERROR CHECKNG define that is used to disable API error checking while non bold values are completely disabled tx
2. Express Logic Inc gt 326 tx_thread_execute_ptr 267 tx_thread_highest_priority 268 tx thread identify 270 tx thread info get 270 tx thread initialize 270 tx thread interrupt control 270 tx thread lowest bit 268 tx thread preempt check 270 tx thread preempt disable 269 tx thread preempted map 268 tx thread preemption change 271 tx thread priority change 271 tx thread priority list 269 tx thread priority map 268 tx thread relinquish 271 tx thread resume 271 tx thread resume api 271 tx thread schedule 271 ix thread shell entry 272 ix thread sleep 272 tx thread special string 269 tx thread stack build 272 tx thread suspend 272 ix thread suspend api 271 tx thread system return 272 tx thread system stack ptr 267 tx thread system state 268 tx thread terminate 272 tx thread time slice 273 tx thread time slice change 273 tx thread timeout 273 tx thread wait abort 273 tx time get 278 tx time set 278 tx timer activate 277 tx timer activate api 278 tx timer change 278 tx timer create 278 tx timer created count 277 tx timer created ptr 277 tx timer current ptr 276 tx timer deactivate 278 tx timer deactivate api 278 tx timer delete 278 ix timer expired 276 tx timer expired time slice 275 TETTES User Guide tx timer info get 279 tx timer initialize 279 tx timer interrupt 279 tx timer list 275
3. Indicates ThreadX Usage FIGURE 3 Memory Area Example The constant area contains various compiled constants including strings defined or referenced within the program In addition this area contains the initial copy of the initialized data area During the compiler s initialization process this portion of the constant area is used to setup the initialized data area in RAM The constant area usually follows the instruction area and is often located in ROM Express Logic Inc 48 Dynamic Memory Usage Initialization i Functional Components of ThreadX The initialized data and uninitialized data areas contain all of the global and static variables These areas are always located in RAM The system stack is generally setup immediately following the initialized and uninitialized data areas The system stack is used by the compiler during initialization and then by ThreadX during initialization and subsequently in ISR processing As mentioned before dynamic memory usage is under direct control of the application Control blocks and memory areas associated with stacks queues and memory pools can be placed anywhere in the target s memory space This is an important feature because it facilitates easy utilization of different types of physical memory For example suppose a target hardware environment has both fast memory and slow memory If the application needs extra performance for a high priority
4. x Hk Hk FUNCTION tx thread create AUTHOR William E Lamie Express Logic DESCRIPTION RELEASE PORTABLE C 3 0 x This function creates a thread and places it on the list of created threads INPUT thread ptr name entry function entry input stack start stack size priority preempt threshold time slice auto start OUTPUT return status CALLS tx thread stack build tx thread resume tx thread system return CALLED BY Application Code tx timer initialize RELEASE HISTORY DATE NAME 12 31 1996 William E Lamie 7 Thread control block pointer Pointer to thread name string Entry function of the thread 32 bit input value to thread Pointer to start of stack Stack size in bytes Priority of thread 0 31 Preemption threshold Thread time slice value Automatic start selection x Thread create return status Build initial thread stack Resume automatic start thread Return to system on preemption Ef Create system timer thread x DESCRIPTION Initial Version 3 0 k k k k k k k k k k k k k k k k k kok K k k K K kok kok KOK
5. See Also tx byte allocate tx byte pool create tx byte pool delete tx byte pool prioritize tx byte release Express Logic Inc 116 Description of ThreadX Services tx byte pool prioritize Prioritize the byte pool suspension list Prototype UINT tx byte pool prioritize TX BYTE POOL pool ptr Description This service places the highest priority thread suspended for memory on this pool at the front of the suspension list All other threads remain in the same FIFO order they were suspended in Input Parameters pool ptr Pointer to a memory pool control block Return Values TX SUCCESS 0x00 Successful memory pool prioritize TX POOL ERROR 0x02 Invalid memory pool pointer Allowed From Initialization threads timers and ISRs Preemption Possible No ELITSE gt User Guide Memory Bytes 117 Example TX BYTE POOL my pool UINT status Ensure that the highest priority thread will receive the next free memory from this pool Status tx byte pool prioritize amp my pool If status equals TX SUCCESS the highest priority suspended thread is at the front of the list The next tx byte release call will wake up this thread if there is enough memory to satisfy its request See Also tx byte allocate tx byte pool create tx byte pool delete tx byte pool info get tx byte release Express Logic Inc 118 Description of ThreadX Services tx byte release Release bytes back
6. ERES User Guide Message Queues 155 Preemption Possible No Example TX QUEUE my queue CHAR name ULONG enqueued TX THREAD first suspended ULONG suspended count TX QUEUE next queue UINT status Retrieve information about a the previously created message queue my queue status tx queue info get amp my queue amp name amp enqueued amp first suspended amp suspended count amp next queue If status equals TX SUCCESS the information requested is valid See Also tx queue create tx queue delete tx queue flush tx queue front send tx queue prioritize tx queue receive tx queue send Express Logic Inc 156 Description of ThreadX Services tx queue prioritize Prioritize queue suspension list Prototype UINT tx queue prioritize TX QUEUE queue ptr Description This service places the highest priority thread suspended for a message or to place a message on this queue at the front of the suspension list All other threads remain in the same FIFO order they were suspended in Input Parameters queue ptr Pointer to a previously created message queue Return Values TX SUCCESS 0x00 Successful queue prioritize TX QUEUE ERROR 0x09 Invalid message queue pointer Allowed From Initialization threads timers and ISRs Preemption Possible No ELITSE gt User Guide Message Queues 157 Example TX QUEUE my queue UINT status Ensure that the hig
7. Return Values TX SUCCESS 0x00 Successful semaphore put TX SEMAPHORE ERROR Ox0C Invalid pointer to counting semaphore Allowed From Initialization threads timers and ISRs Preemption Possible Yes rin d User Guide Counting Semaphores 175 Example TX SEMAPHORE my semaphore UINT status Increment the counting semaphore my semaphore status tx semaphore put amp my semaphore If status equals TX SUCCESS the semaphore count has been incremented Of course if a thread was waiting it was given the semaphore instance and resumed See Also tx semaphore create tx semaphore delete tx semaphore info get tx semaphore prioritize tx semaphore get Express Logic Inc 176 Description of ThreadX Services tx thread create Create an application thread Prototype UINT tx thread create TX THREAD thread ptr CHAR name ptr VOID entry function ULONG ULONG entry input VOID stack start ULONG stack size UINT priority UINT preempt threshold ULONG time slice UINT auto start Description This service creates an application thread that starts execution at the specified task entry function The stack priority preemption threshold and time slice are among the attributes specified by the input parameters In addition the initial execution state of the thread is also specified Input Parameters thread ptr Pointer to a thread control block name ptr Pointer t
8. Threads 3 and 4 243 are also the only threads that are ready for execution most of the time They are also the only threads created with time slicing lines 74 and 82 Each thread is allowed to execute for a maximum of 4 timer ticks before the other thread is executed Threads 3 and 4 Thread 5 i The function thread 3 and 4 entry marks the entry point of both thread 3 and thread 4 lines 246 280 Both threads have a priority of 8 which makes them the third and fourth threads in the demonstration system to execute The processing for each thread is the same incrementing its counter getting semaphore 0 sleeping for 2 timer ticks releasing semaphore 0 and repeating the sequence Notice that each thread suspends whenever semaphore 0 is unavailable line 264 Also both threads use the same function for their main processing This presents no problems because they both have their own unique stack and C is naturally reentrant Each thread determines which one it is by examination of the thread input parameter line 258 which is setup when they are created lines 102 and 109 It is also reasonable to obtain the current thread point during thread execution and compare it with the control block s address to determine thread identity The function thread 5 entry marks the entry point of the thread lines 283 305 Thread 5 is the second thread in the demonstration system to execute Its processing consists of incrementi
9. 232 IIO Drivers for ThreadX the buffer If the next position is past the end of the buffer the write pointer is set to the beginning of the buffer The queue full condition is handled by cancelling the write pointer advancement if the new write pointer is the same as the read pointer Application input byte requests to the driver first examine the read and write pointers of the input buffer If the read and write pointers are identical the buffer is empty Otherwise if the read pointer is not the same the byte pointed to by the read pointer is copied from the input buffer and the read pointer is advanced to the next buffer location If the new read pointer is past the end of the buffer it is reset to the beginning Figure 12 shows the logic for the circular input buffer UCHAR tx input buffer MAX SIZE UCHAR tx input write ptr UCHAR tx input read ptr Initialization 69 me ES DE mpu sur eri DE tx input read ptr amp tx input buffer 0 Input byte ISR UCHAR alpha has character from device 5195 tx input write ptr alpha if tx input write ptr gt amp tx input buffer MAX SIZE 1 Ex input write ptr amp tx input buffer 0 Wrap aie ex mole Vee joe FASE tx input write ptr save ptr Butter full Retrieve input byte from buffer ie iee_sliayoybhe_ieeerel e 859 move viealee per alpha
10. ERIS User Guide Dividing the Application Ease of Use Improve Time to market Protecting the Software Investment ThreadX Benefits 27 In control loop based applications each developer must have an intimate knowledge of the entire application s run time behavior and requirements This is because the processor allocation logic is dispersed throughout the entire application As an application increases in size or complexity it becomes impossible for all developers to remember the precise processing requirements of the entire application ThreadX frees each developer from the worries associated with processor allocation and allows them to concentrate on their specific piece of the embedded application In addition ThreadX forces the application to be divided into clearly defined threads By itself this division of the application into threads makes development much simpler ThreadX is designed with the application developer in mind The ThreadX architecture and service call interface are designed to be easily understood As a result ThreadX developers can quickly use its advanced features All of the benefits of ThreadX accelerate the software development process ThreadX takes care of most processor issues thereby removing this effort from the development schedule All of this results in a faster time to market Because of its architecture ThreadX is easily ported to new processor environments This coupled with t
11. Each of these counters should continue to increase as the demonstration executes with thread 1 counter and thread 2 counter increasing at the fastest rate Distribution file demo c This section displays the complete listing of demo c including the line numbers referenced throughout this chapter Express Logic Inc 246 Demonstration System for ThreadX 000 This is a small demo of the high performance ThreadX kernel It includes examples of eight 001 threads of different priorities using a message queue semaphore mutex event flags group 002 byte pool and block pool 003 004 include tx_api h 005 006 define DEMO STACK SIZE 1024 007 define DEMO BYTE POOL SIZE 9120 008 define BLOCK POOL SIZE 100 009 define DEMO QUEUE SIZE 100 010 011 Define the ThreadX object control blocks 012 013 TX THREAD thread 0 014 TX THREAD thread 1 015 TX THREAD thread 2 016 TX THREAD thread 3 017 TX THREAD thread 4 018 TX THREAD thread 5 019 TX THREAD thread 6 020 TX THREAD thread 7 021 QUEUE queue 0 022 TX SEMAPHORE semaphore 0 023 TX MUTEX mutex 0 024 EVENT FLAGS GROUP event flags 0 025 TX BYTE POOL byte pool 0 026 TX BLOCK POOL block pool 0 027 028 Define the counters used in the demo application 029 030 ULONG thread 0 counter 031 ULONG thread 1 counter 032 ULONG thread 1 messages sent 033 ULONG thread 2 counter 034 ULONG thread 2 m
12. Express Logic Inc 248 Demonstration System for ThreadX 144 tx semaphore create amp semaphore 0 semaphore 0 1 145 146 Create the event flags group used by threads 1 and 5 147 tx event flags create amp event flags 0 event flags 0 148 149 Create the mutex used by thread 6 and 7 without priority inheritance 150 tx mutex create amp mutex 0 mutex 0 TX NO INHERIT 151 152 Allocate the memory for a small block pool 153 tx byte allocate amp byte pool 0 amp pointer DEMO BLOCK POOL SIZE TX NO WAIT 154 155 Create a block memory pool to allocate a message buffer from 156 tx block pool create amp block pool 0 block pool 0 sizeof ULONG pointer 157 DEMO BLOCK POOL SIZE 158 159 Allocate a block and release the block memory 160 tx block allocate amp block pool 0 amp pointer TX NO WAIT 161 162 Release the block back to the pool 163 tx block release pointer 164 165 166 Define the test threads 167 void thread 0 entry ULONG thread input 168 169 170 UINT status 171 172 173 This thread simply sits in while forever sleep loop 174 while 1 175 176 177 Increment the thread counter 178 thread 0 counter 179 180 Sleep for 10 ticks 181 tx thread sleep 10 182 183 Set event flag 0 to wakeup thread 5 184 Status tx event flags set amp event flags 0 0x1 TX OR 185 186 Check sta
13. Prototype UINT tx thread delete TX THREAD thread ptr Description This service deletes the specified application thread Since the specified thread must be in a terminated or completed state this service cannot be called from a thread attempting to delete itself associated with the thread s stack which is available after this service completes In addition the application must prevent use of a deleted thread It is the application s responsibility to manage the memory area Input Parameters thread ptr Pointer to a previously created application thread Return Values TX SUCCESS 0x00 Successful thread deletion TX THREAD ERROR 0x0E Invalid application thread pointer TX DELETE ERROR 0x11 Specified thread is not in a terminated or completed state TX CALLER ERROR 0x13 Invalid caller of this service Allowed From Threads and timers Preemption Possible No ELITS a gt User Guide Thread Control 181 Example TX THREAD my thread UINT status Delete an application thread whose control block is my thread Assume that the thread has already been created with a call to tx thread create Status tx thread delete amp my thread If status equals TX SUCCESS the application thread is deleted See Also tx thread create tx thread identify tx thread info get tx thread preemption change tx thread priority change tx thread relinquish tx thread resume tx thread sleep tx
14. TX THREAD my thread UINT status Create a thread of priority 15 whose entry point is my thread entry This thread s stack area is 1000 bytes in size starting at address 0x400000 The preemption threshold is setup to allow preemption at priorities above 15 Time slicing is disabled This thread is automatically put into a ready condition status tx thread create amp my thread my thread name my thread entry 0x1234 VOID 0x400000 1000 15 15 TX NO TIME SLICE TX AUTO START If status equals TX SUCCESS my thread is ready for execution Thread s entry function When my thread actually begins execution control is transferred to this function VOID my thread entry ULONG initial input When we get here the value of initial input is 0x1234 See how this was specified during creation The real work of the thread including calls to other function should be called from here When the this function returns the corresponding thread is placed into a completed state and suspended See Also tx_thread_delete tx_thread_identify tx_thread_info_get tx_thread_preemption_change tx_thread_priority_change tx_thread_relinquish tx_thread_resume tx_thread_sleep tx_thread_suspend tx_thread_terminate tx_thread_time_slice_change tx_thread_wait_abort Express Logic Inc 180 Description of ThreadX Services tx thread delete Delete an application thread
15. function calls 59 function prototypes 259 G global data 260 global variables 48 globals 62 Green Hills MULTI configuration options 38 debugger 39 stack usage tools 37 Green Hills MULTI build file event logging for ThreadX demo 32 event logging throughout ThreadX C library 32 how to build ThreadX C library 32 initialization file tx ill 34 ThreadX demo 32 Green Hills MULTI development environment 29 Green Hills MULTI tools 31 H hardware devices 224 hardware interrupt 46 heterogeneous 54 hidden system thread 85 high performance 256 high throughput I O 235 high frequency interrupts 88 highly portable 27 Hitachi SH reset 36 host computers 30 host considerations 30 host machines 30 I I O buffer 234 I O buffering 231 I O drivers 223 224 I O error counts 226 improved responsiveness 25 increased throughput 26 information about the ThreadX port 31 In house kernels 23 initial execution 241 initialization 44 45 48 initialization component 266 initialization process 48 Initialize 259 initialized data 46 48 in line assembly 256 input bytes 226 input output lists 236 installation of ThreadX 33 instruction 46 instruction area 46 interrupt control 86 299 interrupt frequency 237 interrupt latency 88 interrupt management 237 interrupt service routines 44 45 interrupting 55 interrupts 44 50 85 Express Logic Inc 330 invalid pointer 62 ISR template 87 ISRs 44 80 229 J JTAG
16. the high performance embedded kernel User Guide for Green Hills MULTI Users Express Logic Inc 858 613 6640 Toll Free 888 THREADX FAX 858 521 4259 http www expresslogic com 1997 2003 by Express Logic Inc All rights reserved This document and the associated ThreadX software are the sole property of Express Logic Inc Each contains proprietary information of Express Logic Inc Reproduction or duplication by any means of any portion of this document without the prior written consent of Express Logic Inc is expressly forbidden Express Logic Inc reserves the right to make changes to the specifications described herein at any time and without notice in order to improve design or reliability of ThreadX The information in this document has been carefully checked for accuracy however Express Logic Inc makes no warranty pertaining to the correctness of this document Trademarks ThreadX is a registered trademark of Express Logic Inc and picokernel and preemption threshold are trademarks of Express Logic Inc Green Hills Software and the Green Hills logo are trademarks and MULTI is a registered trademark of Green Hills Software Inc All other product and company names are trademarks or registered trademarks of their respective holders Warranty Limitations Express Logic Inc makes no warranty of any kind that the ThreadX products will meet the USER s requirements or will operate in the manner specif
17. tx thread sleep tx thread suspend tx thread terminate tx thread wait abort Express Logic Inc 204 Description of ThreadX Services tx thread wait abort Abort suspension of specified thread Prototype UINT tx thread wait abort TX THREAD thread ptr Description This service aborts sleep or any other object suspension of the specified thread If the wait is aborted a TX WAIT ABORTED value is returned from the service that the thread was waiting on Note that this service does not release pure suspension that is made by I the tx thread suspend service Input Parameters thread ptr Pointer to a previously created application thread Return Values TX SUCCESS 0x00 Successful thread wait abort TX THREAD ERROR OxOE Invalid application thread pointer TX WAIT ABORT ERROR 0x1B Specified thread is not in a waiting state Allowed From Initialization threads timers and ISRs Preemption Possible Yes TID User Guide Thread Control 205 Example TX THREAD my thread UINT status Abort the suspension condition of my thread status tx thread wait abort amp my thread If status equals TX SUCCESS the thread is now ready again with a return value showing its suspension was aborted TX WAIT ABORTED See Also tx thread create tx thread delete tx thread identify tx thread info get tx thread preemption change tx thread priority change tx thread relinquish
18. 176 184 tx thread current ptr 59 65 tx thread delete 180 204 tx thread id 263 tx thread identify 59 87 182 tx thread info get 87 tx thread preemption change 188 tx thread priority change 190 tx thread relinquish 54 192 tx thread resume 194 tx thread sleep 196 tx thread suspend 198 tx thread terminate 53 200 tx thread time slice change 202 tx thread wait abort 87 TX TI C 270 TX TIC 270 TX TIDE 270 TX TIDE C 270 TX TIG C 270 TX TIM H 275 tx tim h 261 TX TIMCH C 278 TX TIMCR C 278 TX TIMD C 278 tx time get 85 87 206 tx time se 85 tx time set 85 87 208 TX TIMEG C 278 TX TIMER 84 tx timer activate 87 210 220 tx timer change 87 212 tx timer create 214 tx timer deactivate 87 216 tx timer delete 218 tx timer info get 87 TX TIMES C 278 TX TIMI C 279 TX TIMIG C 279 TX TIMIN 279 TX TPC 270 TX TPCH C 271 TX TPRCH C 271 TX TR C 271 TX TRA C 271 TX TREL C 271 TX TS 271 TX TSA C 271 TX TSB 272 TX TSE C 272 TX TSLE C 272 TX TSR 272 TX TSUS C 272 TX TT C 272 TX TTE C 279 TX TTO C 273 TX TTS C 273 TX TTSC C 273 TX TWA C 273 txe bld 32 39 40 TXE BA C 292 Express Logic Inc 336 TXE BPC C 292 TXE BPD C 292 TXE BPIG C 292 TXE BPP C 292 TXE BR C 292 TXE BTYA C 295 TXE BYTC C 295 TXE BYTD C 295 TXE BYTG C 295 TXE BYTP C 295 TXE BYTR C 295 TXE EFC C 289 TXE EFD C 290 TXE EFG C 290 TXE EFIG C 290 TXE EFS C 290 TXE MD C 287 TXE MIG C 287 TXE M
19. 2 Installation and Use of ThreadX 29 m Host Considerations 30 m Target Considerations 30 m Product Distribution 31 m ThreadX Installation 33 m Using ThreadX 33 m Small Example System 35 m Troubleshooting 37 m Configuration Options 38 m ThreadX Version ID 40 3 Functional Components of ThreadX 41 m Execution Overview 44 Initialization 44 Thread Execution 44 Interrupt Service Routines ISR 44 Initialization 45 Application Timers 46 m Memory Usage 46 Static Memory Usage 46 Dynamic Memory Usage 48 m Initialization 48 System Reset 49 Development Tool Initialization 49 main 49 tx kernel enter 49 Application Definition Function 50 Interrupts 50 Thread Execution 50 Thread Execution States 52 Thread Priorities 54 TETEN User Guide Contents Thread Scheduling 54 Round Robin Scheduling 54 Time Slicing 55 Preemption 55 Preemption Threshold 56 Priority Inheritance 57 Thread Creation 57 Thread Control Block TX THREAD 57 Currently Executing Thread 59 Thread Stack Area 59 Memory Pitfalls 61 Reentrancy 62 Thread Priority Pitfalls 62 Priority Overhead 64 Debugging Pitfalls 65 m Message Queues 65 Creating Message Queues 66 Message Size 66 Message Queue Capacity 66 Queue Memory Area 66 Thread Suspension 67 Queue Control Block TX QUEUE 67 Message Destination Pitfall 68 m Counting Semaphores 68 Mutual Exclusion 68 Event Notification 69 Creating Counting Semaphores
20. 304 305 306 307 void thread 6 and 7 entry ULONG thread input 308 309 310 UINT status 311 312 313 This function is executed from thread 6 and thread 7 As the loop 314 below shows these function compete for ownership of mutex 0 315 while 1 316 317 318 Increment the thread counter 319 if thread input 6 320 thread 6 counter 321 else 322 thread 7 counter 323 324 Get the mutex with suspension 325 status tx mutex get amp mutex 0 TX WAIT FOREVER 326 327 Check status 328 if status TX SUCCESS 329 break 330 331 Get the mutex again with suspension This shows 332 that an owning thread may retrieve the mutex it 333 owns multiple times 334 Status tx mutex get amp mutex 0 TX WAIT FOREVER 335 336 Check status 337 if status TX SUCCESS 338 break 339 340 Sleep for 2 ticks to hold the mutex 341 tx thread sleep 2 342 343 Release the mutex 344 status tx mutex put amp mutex 0 345 346 Check status 347 if status TX SUCCESS 348 break 349 350 Release the mutex again This will actually 351 release ownership since it was obtained twice 352 status tx mutex put amp mutex 0 353 354 Check status 355 if status TX SUCCESS 356 break 357 358 TETTES User Guide Internal Composition of ThreadX Source code products without supporting documentatio
21. Each mutex is a public resource ThreadX places no constraints on how mutexes are used ThreadX mutexes are used solely for mutual exclusion Unlike counting semaphores mutexes have no use as a method for event notification ERIS User Guide Mutex Mutual Exclusion Creating Mutexes Thread Suspension Mutexes 73 Similar to the discussion in the counting semaphore section mutual exclusion pertains to controlling the access of threads to certain application areas also called critical sections or application resources When available a ThreadX mutex will have an ownership count of 0 Once the mutex is obtained by a thread the ownership count is incremented once for every get operation performed on the mutex and decremented for every put operation ThreadX mutexes are created either during initialization or during run time by application threads The initial condition of a mutex is always available Mutex creation is also where the determination is made as to whether or not the mutex implements priority inheritance Application threads can suspend while attempting to perform a get operation on a mutex already owned by another thread Once the same number of put operations are performed by the owning thread the suspended thread s get operation is performed giving it ownership of the mutex and the thread is resumed If multiple threads are suspended on the same mutex they are resumed in the same order they were s
22. The number of memory blocks in a pool is a function of the block size and the total number of bytes in the memory area supplied during creation The capacity of a pool is calculated by dividing the block size including padding and the pointer overhead bytes into the total number of bytes in the supplied memory area As mentioned before the memory area for the block pool is specified during creation Like other memory areas in ThreadX it can be located anywhere in the target s address space This is an important feature because of the considerable flexibility it gives the application For example suppose that a communication product has a high speed memory area for I O This memory area is easily managed by making it into a ThreadX memory block pool Application threads can suspend while waiting for a memory block from an empty pool When a block is returned to the pool the suspended thread is given this block and resumed el gt User Guide Memory Block Pool Control Block TX BLOCK POOL Overwriting Memory Blocks Memory Byte Pools 79 If multiple threads are suspended on the same memory block pool they are resumed in the order they were suspended FIFO However priority resumption is also possible if the application calls tx block pool prioritize prior to the block release call that lifts thread suspension The block pool prioritize service places the highest priority thread at the front of the suspension list wh
23. circular buffers 231 233 circular byte buffers 231 circular output buffer 233 coding conventions 260 comments 264 compiler 46 completed 52 53 completed state 53 component body functions 260 Express Logic Inc 328 component constants 259 component initialization 260 component methodology 256 258 component specification file 259 conditional compilation options 40 configuration options 38 constant 46 constant area 47 consumer 69 context 59 context switch overhead 64 context switches 25 64 context switching 26 257 control loop based applications 27 corrupt memory 61 counting semaphores 68 69 70 73 creating application timers 84 creating counting semaphores 69 creating event flag groups 76 creating memory block pools 77 creating memory byte pools 80 creating message queues 66 creating mutexes 73 critical sections 56 68 73 current device status 226 currently executing thread 59 Customer Support Center 20 D data structures 31 data types 259 deadlock 70 74 deadlock condition 70 deadly embrace 70 74 avoiding 71 debug connection options 30 debug interface 30 debugging multi threaded applications 65 debugging pitfalls 65 de fragmentation 80 demo application 31 demo bld 32 35 36 37 demo c 31 35 240 245 demo con 35 36 demo ld 32 35 37 TETTES User Guide demo el bld 32 39 demo el ld 32 demonstration system 240 deterministic 77 deterministic response times 25 dev
24. is not available suspend until it becomes available Status tx mutex get amp my mutex TX WAIT FOREVER See Also tx mutex create tx mutex delete tx mutex info get tx mutex prioritize tx mutex put Express Logic Inc 140 Description of ThreadX Services tx mutex info get Retrieve information about a mutex Prototype UINT tx mutex info get MUTEX mutex ptr CHAR name ULONG count TX THREAD owner TX THREAD first suspended ULONG suspended count TX MUTEX next mutex Description This service retrieves information from the specified mutex Input Parameters mutex ptr Pointer to mutex control block name Pointer to destination for the pointer to the mutex s name count Pointer to destination for the ownership count of the mutex owner Pointer to destination for the owning thread s pointer first suspended Pointer to destination for the pointer to the thread that is first on the suspension list of this mutex suspended count Pointer to destination for the number of threads currently suspended on this mutex next mutex Pointer to destination for the pointer of the next created mutex Return Values TX SUCCESS 0x00 Successful mutex information retrieval TX MUTEX ERROR 0x1C Invalid mutex pointer TX PTR ERROR 0x03 Invalid pointer NULL for any destination pointer ERIS User Guide Mutex 141 Allowed From Initialization threads timers and ISRs Pre
25. mutex ptr Pointer to a previously created mutex wait option Defines how the service behaves if the mutex is already owned by another thread The wait options are defined as follows TX NO WAIT 0x00000000 TX WAIT FOREVER OxFFFFFFFF timeout value 0x00000001 through OxFFFFFFFE Selecting TX NO WAIT results in an immediate return from this service regardless of whether or not it was successful This is the only valid option if the service is called from Initialization Selecting TX WAIT FOREVER causes the calling thread to suspend indefinitely until the mutex is available Selecting a numeric value 1 OxFFFFFFFE specifies the maximum number of timer ticks to stay suspended while waiting for the mutex ERIS User Guide Mutex 139 Return Values TX SUCCESS 0x00 Successful mutex get operation TX DELETED 0x01 Mutex was deleted while thread was suspended TX NOT AVAILABLE 0x1D Service was unable to get ownership of the mutex TX WAIT ABORTED 0x1A X Suspension was aborted by another thread timer or ISR TX MUTEX ERROR 0x1C Invalid mutex pointer TX WAIT ERROR 0x04 A wait option other than TX NO WAIT was specified on a call from a non thread TX CALLER ERROR 0x13 Invalid caller of this service Allowed From Initialization threads and timers Preemption Possible Yes Example TX MUTEX my mutex UINT status Obtain exclusive ownership of the mutex my mutex If the mutex my mutex
26. static memory 46 static memory usage 46 static variables 48 statics 62 steps to build a ThreadX application 34 suspended 52 suspended state 52 el gt User Guide suspension 87 system description 256 system entry 258 system equates 31 system include files 257 system reset 49 51 system stack 46 48 system stack setup 38 system throughput 26 T target considerations 30 target hardware 30 target memory for event logging 32 target s address space 59 66 78 81 tasks 24 25 tasks vs threads 24 template for application development 36 terminated 52 terminated state 53 Thread 0 242 Thread 1 242 Thread 2 242 Thread 5 243 thread component 267 thread control 57 thread control services 301 thread counters 37 thread create function 38 thread creation 57 thread execution 44 50 thread execution states 52 thread model 24 thread preemption 52 thread priorities 54 62 Thread Priority Pitfalls 62 thread scheduling 54 thread scheduling loops 44 50 thread stack area 59 thread stacks sizes 60 thread starvation 63 thread state transition 52 thread states 52 thread suspension 67 69 70 76 78 81 237 thread s control block 57 thread s stack 57 59 thread s stack area 59 threads 24 25 27 50 54 57 259 Threads 3 and 4 243 ThreadX primary purpose of 24 ThreadX ANSI C library 257 ThreadX benefits 25 improve time to market 27 ThreadX C include files 316 ThreadX C library
27. 225 Driver Access 225 Driver Input 225 Driver Output 225 Driver Interrupts 226 Driver Status 226 Driver Termination 226 m Simple Driver Example 226 Simple Driver Initialization 226 Simple Driver Input 228 Simple Driver Output 229 Simple Driver Shortcomings 230 m Advanced Driver Issues 231 I O Buffering 231 Circular Byte Buffers 231 Circular Buffer Input 231 Circular Output Buffer 233 Buffer I O Management 234 TX IO BUFFER 234 Buffered MO Advantage 235 Buffered Driver Responsibilities 235 Interrupt Management 237 Thread Suspension 237 6 Demonstration System for ThreadX 239 m Overview 240 m Application Define 240 Initial Execution 241 m Thread 0 242 m Thread 1 242 Express Logic Inc 8 ThreadX m Thread 2 242 m Threads and 4 243 m Thread 5 243 m Threads 6 and 7 244 m Observing the Demonstration 244 Distribution file demo c 245 7 Internal Composition of ThreadX 251 m ThreadX Design Goals 256 Simplicity 256 Scalability 256 High Performance 256 ThreadX ANSI C Library 257 System Include Files 257 System Entry 258 Application Definition 258 m Software Components 258 ThreadX Components 259 Component Specification File 259 Component Initialization 260 Component Body Functions 260 m Coding Conventions 260 ThreadX File Names 261 ThreadX Name Space 261 ThreadX Constants 262 ThreadX Struct and Typedef Names 262 ThreadX Member Names 263 ThreadX Global Data 2
28. 324 ERIS gt User Guide ASCII Character Codes 324 ASCII Character Codes in HEX most significant nibble DEL 3x gt N 10 Os lt E c o G ln k D gt Z x gt N lt lt uu olr zzo c iO N o a MN C A o 0 HAS lola Lu GN c x Z m Z m Oo O lt gt F lt 215 0 wm Q Z Li O u T x x 2 O ii F O Z O Lili u K O 2 1 0 ul ul lt m m T j gt O or c G onm o lt m O Q ul u juediubis jseo ELITSE gt User Guide Index Symbols tx thread context restore 88 tx thread context save 88 application ISR entry 88 tx block allocate 291 ix block pool cleanup 291 tx block pool create 291 tx block pool created count 291 tx block pool created ptr 291 ix block pool delete 291 tx block pool info get 291 tx block pool initialize 291 ix block pool prioritize 292 tx block release 292 ix byte allocate 293 tx byte pool cleanup 294 tx byte pool create 293 tx byte pool created count 293 tx byte pool created ptr 293 tx byte pool delete 294 tx byte pool info get 294 tx byte pool initialize 294 tx byte pool prioritize 294 tx byte pool search 294 ix byte release 294 tx
29. 50 m Thread Execution 50 Thread Execution States 52 Thread Priorities 54 Thread Scheduling 54 Round Robin Scheduling 54 Time Slicing 55 Preemption 55 Preemption Threshold 56 Priority Inheritance 57 Thread Creation 57 ERIS User Guide 42 Functional Components of ThreadX Thread Control Block TX THREAD 57 Currently Executing Thread 59 Thread Stack Area 59 Memory Pitfalls 61 Reentrancy 62 Thread Priority Pitfalls 62 Priority Overhead 64 Debugging Pitfalls 65 m Message Queues 65 Creating Message Queues 66 Message Size 66 Message Queue Capacity 66 Queue Memory Area 66 Thread Suspension 67 Queue Control Block TX QUEUE 67 Message Destination Pitfall 68 Counting Semaphores 68 Mutual Exclusion 68 Event Notification 69 Creating Counting Semaphores 69 Thread Suspension 69 Semaphore Control Block TX SEMAPHORE 70 Deadly Embrace 70 Priority Inversion 72 Mutexes 72 Mutex Mutual Exclusion 73 Creating Mutexes 73 Thread Suspension 73 Mutex Control Block TX MUTEX 74 Deadly Embrace 74 Priority Inversion 74 Event Flags 75 Creating Event Flag Groups 76 Thread Suspension 76 Event Flag Group Control Block TX EVENT FLAGS GROUP 76 Memory Block Pools 77 ERIS User Guide Creating Memory Block Pools 77 Memory Block Size 78 Pool Capacity 78 43 Pool s Memory Area 78 Thread Suspension 78 Memory Block Pool Control Block TX BLOCK POOL 79 Overwriting Memory Blocks
30. BLOCK POOL next pool tx block pool prioritize TX BLOCK POOL pool ptr tx block release VOID block ptr ELITS gt User Guide Event Flag Services Interrupt Control Message Queue Services UINT UINT UINT UINT UINT UINT UINT UINT UINT UINT UINT UINT UINT UINT ThreadX API Services 299 tx event flags create TX EVENT FLAGS GROUP group ptr CHAR name ptr tx event flags delete TX EVENT FLAGS GROUP group ptr tx event flags get EVENT FLAGS GROUP group ptr ULONG requested flags UINT get option ULONG actual flags ptr ULONG wait option tx event flags info get EVENT FLAGS GROUP group ptr CHAR name ULONG current flags TX THREAD first suspended ULONG suspended count TX EVENT FLAGS GROUP next group tx event flags set TX EVENT FLAGS GROUP group ptr ULONG flags to set UINT set option tx interrupt control UINT new posture tx queue create TX QUEUE queue ptr CHAR name ptr UINT message size VOID queue start ULONG queue size tx queue delete QUEUE queue ptr tx queue flush TX QUEUE queue ptr tx queue front send TX QUEUE queue ptr VOID source ptr ULONG wait option tx queue info get TX QUEUE queue ptr CHAR name ULONG enqueued ULONG available storage TX THREAD first suspended ULONG suspended count TX QUEUE next queue tx queue prioritize TX QUEUE queue ptr tx queu
31. Demonstration System for ThreadX This chapter contains a description of the demonstration system that is delivered with all ThreadX processor support packages The following lists specific demonstration areas that are covered in this chapter em Overview 240 m Application Define 240 m Thread 0 242 m Thread 1 242 m Thread 2 242 m Threads 3 and 4 243 m Thread 5 243 m Threads 6 and 7 244 m Observing the Demonstration 244 Distribution file demo c 245 ERIS a gt User Guide 240 Demonstration System for ThreadX Overview Each ThreadX product distribution contains a demonstration system that runs on all supported microprocessors This example system is defined in the distribution file demo c and is designed to illustrate how ThreadX is used in an embedded multi thread environment The demonstration consists of initialization eight threads one byte pool one block pool one queue one semaphore one mutex and one event flag group It is worthwhile to mention that except for the thread s stack size the demonstration application is l identical on all ThreadX supported processors The complete listing of demo c including the line numbers referenced throughout the remainder of this chapter is displayed on page 246 and following Application Define The tx application define function executes after the basic ThreadX initialization is complete It is responsible for setting up al
32. KOR K ck KOR K ok KOR R OR R KOR KOR ek OR R KOR KOR KOR R K R KOR KOR R K K FIGURE 16 ThreadX File Header Example 265 Express Logic Inc 266 Internal Composition of ThreadX Initialization Component TX INI H TX IHL C TX IKE C This component is responsible for performing all ThreadX initialization This processing includes setting up processor specific resources as well as calling all of the other component initialization functions Once basic ThreadX initialization is complete the application tx application define function is called to perform application specific initialization The thread scheduling loop is entered after all initialization is complete This is the specification file for the ThreadX Initialization Component All component constants external interfaces and data structures are defined in this file The global data for the initialization component is defined in this file and consists of the following data elements tx initialize unused memory This VOID pointer contains the first memory address available to the application after ThreadX is initialized The contents of this variable is passed into the application s tx application define function This file contains tx initialize high level which is responsible for calling all other ThreadX component initialization functions and the application definition function tx application define This file contains tx initial
33. TX CALLER ERROR 0x13 Invalid caller of this service ELITS a gt User Guide Thread Control 191 Allowed From Threads and timers Preemption Possible Yes Example TX THREAD my thread UINT my old priority UINT status Change the thread represented by my thread to priority 0 status tx thread priority change amp my thread 0 amp my old priority If status equals TX SUCCESS the application thread is now at the highest priority level in the system See Also tx thread create tx thread delete tx thread identify tx thread info get tx thread preemption change tx thread relinquish tx thread resume tx thread sleep tx thread suspend tx thread terminate tx thread time slice change tx thread wait abort Express Logic Inc 192 Description of ThreadX Services tx thread relinquish Relinquish control to other application threads Prototype VOID tx thread relinquish VOID Description This service relinquishes processor control to other ready to run threads at the same or higher priority Input Parameters VOID Return Values VOID Allowed From Threads Preemption Possible Yes TID User Guide Thread Control 193 Example q LONG run counter 1 0 LONG run counter 2 0 q Example of two threads relinquishing control to each other in an infinite loop Assume that both of these threads are ready and have the same priority The run counters w
34. TXE BR C Internal Composition of ThreadX This file contains tx block pool prioritize which is responsible for finding the highest priority thread suspended on a block pool and moving it to the front of the suspension list This file contains tx block release which is responsible for processing block release requests This file contains txe block allocate which is responsible for checking block allocate requests for errors This file contains txe block pool create which is responsible for checking block memory pool create requests for errors This file contains txe block pool delete which is responsible for checking block memory pool delete requests for errors This file contains txe block pool info get which is responsible for checking block pool information retrieval requests for errors This file contains txe block pool prioritize which is responsible for checking block pool prioritize requests for errors This file contains txe block release which is responsible for checking block memory release request for errors ERIS User Guide Byte Memory Component 293 Byte Memory Component TX BYT H TX BYTA C TX BYTC C This component is responsible for all byte memory management activities including byte pool creation deletion byte allocates and byte releases This is the specification file for the ThreadX Byte Memory Component All component constants external interfaces and data str
35. This file contains tx queue flush which is responsible for processing queue flush requests This file contains tx queue front send which is responsible for processing requests to send a message to the front of a queue This file contains tx queue initialize which is responsible for initialization of the queue component This file contains tx queue info get which is responsible for retrieving information about a queue This file contains tx queue prioritize which is responsible for finding the highest priority thread suspended on a queue and placing it at the front of the suspension list This file contains tx queue receive which is responsible for processing queue receive requests Express Logic Inc 282 TX QS C TXE QC C TXE QD C TXE QF C TXE QFS C TXE QIG C TXE QP C TXE QR C Internal Composition of ThreadX This file contains tx queue send which is responsible for processing queue send requests This file contains txe queue create which is responsible for checking queue create requests for errors This file contains txe queue delete which is responsible for checking queue delete requests for errors This file contains txe queue flush which is responsible for checking queue flush requests for errors This file contains txe queue front send which is responsible for checking queue front send requests for errors This file contains txe queue info get which is respons
36. This file contains tx thread sleep which is responsible for processing all application thread sleep requests This file contains tx thread system return which is responsible for saving a thread s minimal context and exiting to the ThreadX scheduling loop This function is processor compiler specific and is written in assembly language This file contains tx thread suspend which is responsible for processing all thread suspend requests from internal ThreadX components and the application software This file contains tx thread terminate which is responsible for processing all thread terminate requests el gt User Guide TX TTO C TX TTS C TX TTSC C TX TWA C TXE TC C TXE TDEL C TXE TIG C TXE TPCH C Thread Component 273 This file contains tx thread timeout which is responsible for processing all suspension time out conditions This file contains tx thread time slice which is responsible for processing thread time slicing This file contains tx thread time slice change which is responsible for requests to change a thread s time slice This file contains tx thread wait abort which is responsible for breaking the wait condition of the specified thread This file contains txe thread create which is responsible for checking the thread create requests for errors This file contains txe thread delete which is responsible for checking the thread delete requests for errors This file cont
37. binary version 32 ThreadX components 259 ThreadX constants 262 ThreadX data types 19 ThreadX design goals 256 ThreadX file header example 265 ThreadX file names 261 ThreadX function names 263 ThreadX global data 263 ThreadX installation 33 ThreadX library 32 ThreadX local data 263 ThreadX managed interrupts 86 ThreadX member names 263 ThreadX name space 261 ThreadX overview 22 ThreadX packages 31 ThreadX port specific assembly language files 322 ThreadX services 89 ThreadX source files 316 ThreadX struct and typedef name 262 ThreadX timer interrupt 37 ThreadX version ID 40 throughput 26 tick counter 85 time 52 time services 301 time slicing 55 time outs 46 67 timer accuracy 84 timer component 275 timer execution 84 timer interrupt setup 30 timer intervals 83 timer services 83 301 timer setup 83 timer ticks 55 83 84 85 timer related functions 30 timer related services 31 timers 50 259 time slice 55 58 time slicing 30 83 troubleshooting 37 tx 49 tx a 32 33 34 35 tx bld 32 35 TX AND CLEAR 75 tx api h 31 33 34 57 67 70 74 76 79 82 84 257 262 tx application define 34 49 50 51 227 240 241 258 266 TX AUTO START 2441 TX BA C 291 TX BLO H 290 tx block allocate 86 94 100 tx block delete 86 TX BLOCK MEMORY 0x08 58 TX BLOCK POOL 79 tx block pool create 96 102 tx block pool delete 98 tx block pool info get 86 tx block pool prioriti
38. block allocate Allocate a fixed size block of memory 94 tx block pool create Create a pool of fixed size memory blocks 96 tx block pool delete Delete fixed size block of memory pool 98 tx block pool info get Retrieve information about block pool 100 tx block pool prioritize Prioritize block pool suspension list 102 tx block release Release a fixed size block of memory 104 tx byte allocate Allocate bytes of memory 106 el gt User Guide 90 Description of ThreadX Services tx byte pool create Create a memory pool of bytes 110 tx byte pool delete Delete a memory pool of bytes 112 tx byte pool info get Retrieve information about byte pool 114 tx byte pool prioritize Prioritize the byte pool suspension list 116 tx byte release Release bytes back to memory pool 118 tx event flags create Create an event flag group 120 tx event flags delete Delete an event flag group 122 tx event flags get Get event flags from event flag group 124 tx event flags info get Retrieve information about event flags group 128 tx event flags set Set event flags in an event flag group 130 tx interrupt control Enables and disables interrupts 132 tx mutex create Create a mutual exclusion mutex 134 tx mutex delete Delete a mutual exclusion mutex 136 tx mutex get Obtain ownership of a mutex 138 tx mutex info get Retrieve information about a mutex 140 tx mutex prioritize Prioritize mutex suspension list 14
39. by one Input Parameters semaphore ptr Pointer to a previously created counting semaphore wait option Defines how the service behaves if there are no instances of the semaphore available i e the semaphore count is zero The wait options are defined as follows TX NO WAIT 0x00000000 TX WAIT FOREVER OxFFFFFFFF timeout value 0x00000001 through OxFFFFFFFE Selecting TX NO WAIT results in an immediate return from this service regardless of whether or not it was successful This is the only valid option if the service is called from a non thread e g initialization timer or ISR Selecting TX WAIT FOREVER causes the calling thread to suspend indefinitely until a semaphore instance is available Selecting a numeric value 1 OxFFFFFFFE specifies the maximum number of timer ticks to stay suspended while waiting for a semaphore instance ERIS User Guide Counting Semaphores 169 Return Values TX SUCCESS 0x00 Successful retrieval of a semaphore instance TX DELETED 0x01 Counting semaphore was deleted while thread was suspended TX NO INSTANCE 0 00 Service was unable to retrieve an instance of the counting semaphore semaphore count is zero TX WAIT ABORTED 0x1A Suspension was aborted by another thread timer or ISR TX SEMAPHORE ERROR Ox0C Invalid counting semaphore pointer TX WAIT ERROR 0x04 A wait option other than TX NO WAIT was specified on a call from a non thread A
40. causes the calling thread to suspend indefinitely until the event flags are available Selecting a numeric value 1 OxFFFFFFFE specifies the maximum number of timer ticks to stay suspended while waiting for the event flags 0x00 Successful event flags get 0x01 Event flag group was deleted while thread was suspended 0x07 Service was unable to get the specified events 0x1A Suspension was aborted by another thread timer or ISR 0x06 Invalid event flags group pointer 0x03 Invalid pointer for actual event flags 0x04 Await option other than TX NO WAIT was specified on a call from a non thread 0x08 Invalid get option was specified Express Logic Inc 126 Description of ThreadX Services Allowed From Initialization threads timers and ISRs Preemption Possible Yes Example TX EVENT FLAGS GROUP my event flags group ULONG actual events UINT status Request that event flags 0 4 and 8 are all set Also if they are set they should be cleared If the event flags are not set this service suspends for a maximum of 20 timer ticks Status tx event flags get amp my event flags group 0x111 TX AND CLEAR amp actual events 20 status equals actual events contains e If stat ls TX SUCCESS tual t tai th actual events obtained See Also tx event flags create tx event flags delete tx event flags info get tx event flags set erin I User Guide Ev
41. event flags cleanup 289 tx event flags create 289 tx event flags created count 288 tx event flags created ptr 288 tx event flags delete 289 tx event flags get 289 tx event flags info get 289 tx event flags initialize 289 tx event flags set 289 tx initialize high level 266 tx initialize kernel enter 258 261 266 tx initialize low level 267 tx initialize unused memory 266 ix mutex cleanup 286 tx mutex create 286 tx mutex created count 286 tx mutex created ptr 286 mutex delete 286 tx mutex get 286 tx mutex info get 287 tx mutex initialize 286 tx mutex prioritize 287 tx mutex priority change 287 tx mutex put 287 tx queue cleanup 281 tx queue create 280 tx queue created count 280 tx queue created ptr 280 tx queue delete 281 tx queue flush 281 tx queue front send 281 tx queue info get 281 tx queue initialize 281 tx queue prioritize 281 tx queue receive 281 x queue send 282 tx semaphore cleanup 284 tx semaphore create 283 tx semaphore created count 283 tx semaphore created ptr 283 tx semaphore delete 284 tx semaphore get 284 tx semaphore info get 284 x semaphore initialize 284 x semaphore prioritize 284 tx semaphore put 284 tx thread context restore 227 tx thread context save 227 270 tx thread create 261 264 tx thread created count 268 tx thread created ptr 268 tx thread current ptr 263 267 270 tx thread delete 270
42. gt User Guide Interrupt Management Thread Suspension Advanced Driver Issues 237 driver This might alleviate some buffer allocation processing inside of the driver In some applications the device interrupt frequency may prohibit writing the ISR in C or to interact with ThreadX on each interrupt For example if it takes 25us to save and restore the interrupted context it would not be advisable to perform a full context save if the interrupt frequency was 50us In such cases a small assembly language ISR is used to handle most of the device interrupts This low overhead ISR would only interact with ThreadX when necessary A similar discussion can be found in the interrupt management discussion at the end of Chapter 3 In the simple driver example presented earlier in this chapter the caller of the input service suspends if a character is not available In some applications this might not be acceptable For example if the thread responsible for processing input from a driver also has other duties suspending on just the driver input is probably not going to work Instead the driver needs to be customized to request processing similar to the way other processing requests are made to the thread In most cases the input buffer is placed on a linked list and an input event message is sent to the thread s input queue Express Logic Inc 238 I O Drivers for ThreadX erin d User Guide CHAPTER 6
43. implementation usually a single periodic hardware interrupt is used is hidden from the application Such timers are used by applications to perform time outs periodics and or watchdog services Just like ISRs application timers most often interrupt thread execution Unlike ISRs however Application Timers cannot interrupt each other Memory Usage Static Memory Usage ThreadX resides along with the application program As a result the static memory or fixed memory usage of ThreadX is determined by the development tools e g the compiler linker and locator Dynamic memory or run time memory usage is under direct control of the application Most of the development tools divide the application program image into five basic areas instruction constant initialized data uninitialized data and system stack Figure 3 on page 47 shows an example of these memory areas It is important to realize that this is only an example The actual static memory layout is specific to the processor development tools and the underlying hardware The instruction area contains all of the program s processor instructions This area is typically the largest and is often located in ROM ERES gt User Guide Memory Usage 47 Static Memory Usage example addresses 0x00000000 Instruction Area ROM Constant Area ROM 0x80000000 Initialized Data Area RAM Uninitialized Data Area RAM System Stack Area
44. of threads to certain application areas also called critical sections or application resources When used for mutual exclusion the current count of a ERIS User Guide if Event Notification Creating Counting Semaphores Thread Suspension Counting Semaphores 69 semaphore represents the total number of threads that are allowed access In most cases counting semaphores used for mutual exclusion will have an initial value of 1 meaning that only one thread can access the associated resource at a time Counting semaphores that only have values of 0 or 1 are commonly called binary semaphores If a binary semaphore is being used the user must prevent the same thread from performing a get operation on a semaphore it already owns A second get would be unsuccessful and could cause indefinite suspension of the calling thread and permanent un availability of the resource It is also possible to use counting semaphores as event notification in a producer consumer fashion The consumer attempts to get the counting semaphore while the producer increases the semaphore whenever something is available Such semaphores usually have an initial value of 0 and won t increase until the producer has something ready for the consumer Counting semaphores are created either during initialization or during run time by application threads The initial count of the semaphore is specified during creation There are no limits on the numb
45. of ThreadX This file contains tx semaphore cleanup which is responsible for processing semaphore suspension time outs semaphore suspended thread termination and thread wait abort requests This file contains tx semaphore delete which is responsible for processing semaphore deletion requests This file contains tx semaphore get which is responsible for processing semaphore get requests This file contains tx semaphore initialize which is responsible for initialization of the semaphore component This file contains tx semaphore info get which is responsible for semaphore information retrieval requests This file contains tx semaphore put which is responsible for semaphore put requests This file contains tx semaphore prioritize which is responsible for finding the highest priority thread suspended on a semaphore and placing it at the front of the suspension list This file contains txe semaphore create which is responsible for checking semaphore create requests for errors el gt User Guide TXE SD C TXE SG C TXE SIG C TXE SP C TXE SPRI C Mutex Component 285 This file contains txe semaphore delete which is responsible for checking semaphore delete requests for errors This file contains txe semaphore get which is responsible for checking semaphore get requests for errors This file contains txe semaphore info get which is responsible for checking semaphore information retrieval request
46. resumed and given a TX DELETED return status associated with the pool which is available after this service completes In addition the application must prevent use of a deleted pool or memory previously allocated from it It is the application s responsibility to manage the memory area Input Parameters pool ptr Pointer to a previously created memory pool Return Values TX SUCCESS 0x00 Successful memory pool deletion TX POOL ERROR 0x02 Invalid memory pool pointer TX CALLER ERROR 0x13 Invalid caller of this service Allowed From Threads Preemption Possible Yes ELITSE gt User Guide Memory Bytes 113 Example TX BYTE POOL my pool UINT status Delete entire memory pool Assume that the pool has already been created with a call to tx byte pool create status tx byte pool delete amp my pool If status equals TX SUCCESS memory pool is deleted See Also tx byte allocate tx byte pool create tx byte pool info get tx byte pool prioritize tx byte release Express Logic Inc 114 Description of ThreadX Services tx byte pool info get Prototype Retrieve information about byte pool UINT tx byte pool info get BYTE POOL pool ptr CHAR name ULONG available ULONG fragments TX THREAD first suspended ULONG suspended count TX BYTE POOL next pool Description This service retrieves information about the specified memory byte pool Inp
47. the MULTI debugger The first step is to connect MULTI to the target by selecting the CONNECT button After the connection is established the demonstration can be downloaded and debugged by selecting the DEBUG button Figure 1 Template for Application Development on page 36 shows the demo bld file loaded the MULTI environment Note that there are several additional files in demo bld namely reset arm and demo con The reset arm file contains the ARM processor s reset vector code as well as the other vectors in architecture Express Logic Inc 36 Installation and Use of ThreadX Each processor support package has its own unique reset file e g reset ppc PowerPC reset mip MIPS reset sh Hitachi SH reset 68 68K ColdFire etc The demo con file contains information that specifies the target connection Connections to actual hardware targets as well as MULTI s extensive set of architecture simulators are specified in this file Builder for demo bld EP File Edit Project Build Debug Target Version Config Windows Help Z c D e gt m AZ Filename File Type Version Control demo bld program reset arm assembly tx ill arm assembly demo c C demo ld linker_file readme txt documentation demo con connections Creating project default bld C release threads demo bld Target arm FIGURE 1 Template for Application Development Alth
48. thread suspend tx thread terminate tx thread time slice change tx thread wait abort Express Logic Inc 182 Description of ThreadX Services tx thread identify Retrieves pointer to currently executing thread Prototype TX THREAD tx thread identify VOID Description This service returns a pointer to the currently executing thread If no thread is executing this service returns a null pointer If this service is called from an ISR the return value represents the thread I running prior to the executing interrupt handler Input Parameters None Return Values thread pointer Pointer to the currently executing thread If no thread is executing the return value is TX NULL Allowed From Threads and ISRs Preemption Possible No TID User Guide Thread Control 183 Example TX THREAD my thread ptr Find out who we are my thread ptr tx thread identify If my thread ptr is non null we are currently executing from that thread or an ISR that interrupted that thread Otherwise this service was called from an ISR when no thread was running when the interrupt occurred See Also tx thread create tx thread delete tx thread info get tx thread preemption change tx thread priority change tx thread relinquish tx thread resume tx thread sleep tx thread suspend tx thread terminate tx thread time slice change tx thread wait abort Express Logic Inc 184 Des
49. time the lower priority thread holds the resource This condition is both deterministic and quite normal However if threads of intermediate priority become active during this priority inversion condition the priority inversion time is no longer deterministic and could cause an application failure There are principally three distinct methods of preventing un deterministic priority inversion in ThreadX First the application priority selections and run time behavior can be designed in a manner that prevents the priority inversion problem Second lower priority threads can utilize preemption threshold to block preemption from intermediate threads while they share resources with higher priority threads Finally threads using ThreadX mutex objects to protect system resources may utilize the optional mutex priority inheritance to eliminate un deterministic priority inversion Express Logic Inc 64 Priority Overhead Functional Components of ThreadX One of the most overlooked ways to reduce overhead in multi threading is to reduce the number of context switches As previously mentioned a context switch occurs when execution of a higher priority thread is favored over that of the executing thread It is worthwhile to mention that higher priority threads can become ready as a result of both external events like interrupts and from service calls made by the executing thread To illustrate the effects thread priorities hav
50. too small The user must come up with the worst case size requirement by examining function call nesting and local variable allocation Of course it is always better to error towards a larger stack area After the application is debugged it is possible to go back and tune the thread stacks sizes if memory is scarce A favorite trick is to preset all stack areas with an easily identifiable data pattern like OXEFEF prior to creating the threads After the application has been thoroughly put through its paces the stack areas can be examined to see how much was actually used by finding the area of the stack where the preset pattern is still intact Figure 7 on page 61 ERIS User Guide Thread Execution 61 shows a stack preset to OxEFEF after thorough thread execution Stack Memory Area another example physical addresses 0x0000F200 Unused Stack Area Typical run time stack growth tx stack ptr Thread s last execution context Local variables and C function nesting Y 0x0000FC00 FIGURE 7 Stack Preset to 0xEFEF Memory Pitfalls The stack requirements for threads can be quite large Therefore it is important to design the application to have a reasonable number of threads Furthermore some care must be taken to avoid excessive stack usage within threads Recursive algorithms and large local data structures should generally be avoided What happens when a stack area is too small In most c
51. tx thread resume tx thread sleep tx thread suspend tx thread terminate tx thread time slice change Express Logic Inc 206 Description of ThreadX Services tx time get Retrieves the current time Prototype ULONG tx time get VOID Description This service returns the contents of the internal system clock Each timer tick increases the internal system clock by one The system clock is set to zero during initialization and can be changed to a specific value by the service tx time set The actual time each timer tick represents is application specific Input Parameters None Return Values system clock ticks Value of the internal free running system clock Allowed From Initialization threads timers and ISRs Preemption Possible No TID User Guide Time Ticks 207 Example ULONG current time Pickup the current system time in timer ticks current time tx time get Current time now contains a copy of the internal system clock See Also tx time set Express Logic Inc 208 Description of ThreadX Services tx time set Sets the current time Prototype VOID tx time set ULONG new time Description This service sets the internal system clock to the specified value Each timer tick increases the internal system clock by one The actual time each timer tick represents is application specific Input Parameters new time New time to put in t
52. tx timer list end 276 tx timer list start 276 tx timer priority 277 tx timer stack size 277 tx timer stack start 276 tx timer system clock 275 278 tx timer thread 276 tx timer thread entry 279 tx timer thread stack area 277 tx timer time slice 275 tx version id 40 257 txe block allocate 292 txe block pool create 292 txe block pool delete 292 txe block pool info get 292 txe block pool prioritize 292 txe block release 292 txe byte allocate 295 txe byte pool create 295 txe byte pool delete 295 txe byte pool info get 295 txe byte pool prioritize 295 txe byte release 295 txe event flags create 289 txe event flags delete 290 txe event flags get 290 txe event flags info get 290 txe event flags set 290 txe mutex create 287 txe mutex delete 287 txe mutex get 287 txe mutex info get 287 txe mutex prioritize 288 txe mutex put 288 txe queue create 282 txe queue delete 282 txe queue flush 282 txe queue front send 282 txe queue info get 282 txe queue prioritize 282 txe queue receive 282 txe queue send 283 txe semaphore create 284 txe semaphore delete 285 txe semaphore get 285 txe semaphore info get 285 txe semaphore prioritize 285 txe semaphore put 285 txe thread create 273 txe thread delete 273 txe thread info get 273 txe thread preemption change 273 txe thread priority change 274 txe thread relinquish 274 txe thread resume api 274 txe thread suspend api 27
53. typically written in assembly language This file contains tx thread delete which is responsible fore deleting a previously created thread This file contains tx thread initialize which is responsible for basic thread component initialization This file contains tx thread interrupt control which is responsible for enabling and disabling processor interrupts This file contains tx thread identify which is responsible for returning the value of tx thread current ptr This file contains tx thread info get which is responsible for returning various information about a thread This file contains tx thread preempt check which determines if preemption occurred while processing a lower level interrupt This function is processor compiler specific and is written in assembly language In addition this function is optional and is not needed for most ports ERIS User Guide TX TPCH C TX TPRCH C TX TR C TX TRA C TX TREL C TX TS S ASM TX TSA C Thread Component 271 This file contains tx thread preemption change which is responsible for changing the preemption threshold of the specified thread This file contains tx thread priority change which is responsible for changing the priority of the specified thread This file contains tx thread resume which is responsible for making the specified thread ready for execution This function is called from other ThreadX components as well as the thread resume
54. 12 Specified thread is not suspended or was previously suspended by a service other than tx thread suspend Allowed From Initialization threads timers and ISRs Preemption Possible Yes TID User Guide Thread Control 195 Example TX THREAD my thread UINT status Resume the thread represented by my thread Status tx thread resume amp my thread If status equals TX SUCCESS the application thread is now ready to execute See Also tx thread create tx thread delete tx thread identify tx thread info get tx thread preemption change tx thread priority change tx thread relinquish tx thread sleep tx thread suspend tx thread terminate tx thread time slice change tx thread wait abort Express Logic Inc 196 Description of ThreadX Services tx thread sleep Suspended current thread for specified time Prototype UINT tx thread sleep ULONG timer ticks Description This service causes the calling thread to suspend for the specified number of timer ticks The amount of physical time associated with a timer tick is application specific This service can only be called only from an application thread Input Parameters timer ticks The number of timer ticks to suspend the calling application thread ranging from 0 through OxFFFFFFFF If 0 is specified the service returns immediately Return Values TX SUCCESS 0x00 Successful thread sleep TX WAIT ABORTED 0x1A Susp
55. 2 ERIS User Guide 91 tx mutex put Release ownership of mutex 144 tx queue create Create a message queue 146 tx queue delete Delete a message queue 148 tx queue flush Empty messages in a message queue 150 tx queue front send Send a message to the front of queue 152 tx queue info get Retrieve information about a queue 154 tx queue prioritize Prioritize queue suspension list 156 tx queue receive Get a message from message queue 158 tx queue send Send a message to message queue 162 tx semaphore create Create a counting semaphore 164 tx semaphore delete Delete a counting semaphore 166 tx semaphore get Get instance from counting semaphore 168 tx semaphore info get Retrieve information about a semaphore 170 tx semaphore prioritize Prioritize semaphore suspension list 172 tx semaphore put Place an instance in counting semaphore 174 tx thread create Create an application thread 176 Express Logic Inc 92 Description of ThreadX Services tx thread delete Delete an application thread 180 tx thread identify Retrieves pointer to executing thread 182 tx thread info get Retrieve information about a thread 184 tx thread preemption change Change preemption threshold of application thread 188 tx thread priority change Change priority of an application thread 190 tx thread relinquish Relinquish control to other application threads 192 tx thread resume Resume suspended applicatio
56. 3 TXE TIG C 273 TXE TPCH C 273 TXE TRA C 274 TXE TREL C 274 TXE TRPC C 274 TXE TSA C 274 TXE TT C 274 el gt User Guide 253 TXE TTSC C 274 TXE TWA C 274 m Timer Component 275 TX TIM H 275 TX TA C 277 TX TAA C 278 TX TD C 278 TX TDA C 278 TX TIMCH C 278 TX TIMCR C 278 TX TIMD C 278 TX TIMEG C 278 TX TIMES C 278 TX TIMI C 279 TX TIMIG C 279 TX TIMIN S ASM 279 TX TTE C 279 TXE TAA C 279 TXE TDA C 279 TXE TIMD C 279 TXE TIMI C 279 TXE TMCH C 280 TXE TMCR C 280 m Queue Component 280 TX QUE H 280 TX QC C 280 TX QCLE C 281 TX QD C 281 TX QF C 281 TX QFS C 281 TX QI C 281 TX QIG C 281 TX QP C 281 TX QR C 281 TX QS C 282 TXE QC C 282 TXE QD C 282 TXE QF C 282 TXE QFS C 282 TXE QIG C 282 TXE QP C 282 TXE QR C 282 Express Logic Inc 254 Internal Composition of ThreadX TXE QS C 283 m Semaphore Component 283 TX SEM H 283 TX SC C 283 TX SCLE C 284 TX SD C 284 TX SG C 284 TX SI C 284 TX SIG C 284 TX SP C 284 TX SPRI C 284 TXE SC C 284 TXE SD C 285 TXE SG C 285 TXE SIG C 285 TXE SP C 285 TXE SPRI C 285 m Mutex Component 285 TX MUT H 285 TX MC C 286 TX MCLE C 286 TX MD C 286 TX MG C 286 TX MI C 286 TX MIG C 287 TX MP C 287 TX MPC C 287 TX MPRI C 287 TXE MC C 287 TXE MD C 287 TXE MG C 287 TXE MIG C 287 TXE MP C 288 TXE MPRI C 288 m Event Flag Component 288 TX EVE H 288 TX EFC C 289 TX EFCLE C 289 TX EFD C 289 TX EFG C 289 ERIS User Guide 255 TX
57. 30 L large local data 61 linker 46 linker control file allocation of target memory for event logging 32 linker control file for specifying where demo application resides in target memory 32 local storage 57 local variable 59 local variables 59 locator 46 logic for circular input buffer 232 logic for circular output buffer 233 logical AND OR 75 low level initialization 49 M main 49 51 main function 49 malloc calls 80 memory 52 memory areas 46 memory block pool control block 79 memory block pools 77 memory block size 78 memory byte pool control block 82 memory byte pools 79 82 memory pitfalls 61 memory pools 48 50 Memory Usage 46 memory usage 46 merged 80 message destination pitfall 68 message queue capacity 66 message queue services 299 TETTES User Guide message queues 65 message size 66 microkernel 22 minimum stack size 59 MIPS reset 36 misuse of thread priorities 62 modifications 23 MULTI architecture simulators 36 MULTI debugger 35 MULTI environment CONNECT button 35 DEBUG button 35 project BUILD button 35 MULTI processor simulation demo system 35 multi threaded 26 52 multi threading 62 64 65 256 mutex component 285 mutex mutual exclusion 73 mutexes 50 52 57 63 72 73 259 mutual exclusion 68 70 72 74 N naming convention 32 non reentrant 62 number of threads 57 O observing the demonstration 244 one shot timer 83 output bytes 226 ove
58. 4 txe thread terminate 274 txe thread time slice change 274 txe thread wait abort 274 txe timer activate api 279 txe timer change 280 txe timer create 280 txe timer deactivate api 279 txe timer delete 279 txe timer info get 279 Numerics 68K ColdFire reset 36 A accelerated development 27 action functions 258 additional host system considerations 31 advanced driver issue 231 after tx application define 241 allocation algorithm 80 allocation of processing 24 ANSI C 22 application compiling 30 downloading 30 application define 240 application definition 258 application definition function 50 application resources 68 73 application specific modifications 23 application timer control block 84 application timers 30 46 83 84 application s entry point 49 applications linking 30 ARM processor reset vector code 35 ASCII character codes in HEX 324 asynchronous events 85 available 73 B binary semaphores 69 72 black box 22 256 block memory 259 block memory component 290 block memory services 298 block size 78 Block TX MUTEX 74 Block TX QUEUE 67 Block TX THREAD 57 buffer I O management 234 buffered driver responsibilities 235 buffered I O advantage 235 buffering messages 66 bypass service call error checking 38 byte memory 259 byte memory component 293 byte memory services 298 C C library 22 256 C pointers 78 80 C source code 22 cache 77 circular buffer input 231
59. 6 void thread 3 and 4 entry ULONG thread input 247 248 249 UINT status 250 251 252 This function is executed from thread 3 and thread 4 As the loop 253 below shows these function compete for ownership of semaphore 0 254 while 1 255 256 257 Increment the thread counter 258 if thread input 3 259 thread 3 counter 260 else 261 thread 4 counter 262 263 Get the semaphore with suspension 264 status semaphore get amp semaphore 0 TX WAIT FOREVER 265 266 Check status 267 if status TX SUCCESS 268 break 269 270 Sleep for 2 ticks to hold the semaphore 271 tx thread sleep 2 272 273 Release the semaphore 274 status semaphore put amp semaphore 0 275 276 Check status 277 if status TX SUCCESS 278 break 279 280 281 282 283 void thread 5 entry ULONG thread input 284 285 286 UINT status 287 ULONG actual flags Express Logic Inc 250 Demonstration System for ThreadX 288 289 290 This thread simply waits for an event in a forever loop 291 while 1 292 293 294 Increment the thread counter 295 thread 5 counter 296 297 Wait for event flag 0 298 Status tx event flags get amp event flags 0 0x1 TX OR CLEAR 299 amp actual flags TX WAIT FOREVER 300 301 Check status 302 if status TX SUCCESS actual flags 0 1 303 break
60. 63 ThreadX Local Data 263 ThreadX Function Names 263 Source Code Indentation 264 Comments 264 Initialization Component 266 TX INI H 266 TX IHL C 266 TX IKE C 266 TX ILL S ASM 267 TETEN User Guide Contents m Thread Component 267 TX THR H 267 TX TC C 269 TX TCR S ASM 269 TX TCS S ASM 270 TX TDEL C 270 TX TI C 270 TX TIC S ASM 270 TX TIDE C 270 TX TIG C 270 TX TPC S ASM 270 TX TPCH C 271 TX TPRCH C 271 TX TR C 271 TX TRA C 271 TX TREL C 271 TX TS S ASM 271 TX TSA C 271 TX TSB S ASM 272 TX TSE C 272 TX TSLE C 272 TX TSR S ASM 272 TX TSUS C 272 TX TT C 272 TX TTO C 273 TX TTS C 273 TX TTSC C 273 TX TWA C 273 TXE TC C 273 TXE TDEL C 273 TXE TIG C 273 TXE TPCH C 273 TXE TRA C 274 TXE TREL C 274 TXE TRPC C 274 TXE TSA C 274 TXE TT C 274 TXE TTSC C 274 TXE TWA C 274 m Timer Component 275 TX TIM H 275 Express Logic Inc 10 ThreadX TX TA C 277 TX TAA C 278 TX TD C 278 TX TDA C 278 TX TIMCH C 278 TX TIMCR C 278 TX TIMD C 278 TX TIMEG C 278 TX TIMES C 278 TX TIMI C 279 TX TIMIG C 279 TX TIMIN S ASM 279 TX TTE C 279 TXE TAA C 279 TXE TDA C 279 TXE TIMD C 279 TXE TIMI C 279 TXE TMCH C 280 TXE TMCR C 280 m Queue Component 280 TX QUE H 280 TX QC C 280 TX QCLE C 281 TX QD C 281 TX QF C 281 TX QFS C 281 TX QI C 281 TX QIG C 281 TX QP C 281 TX QR C 281 TX QS C 282 TXE QC C 282 TXE QD C 282 TXE QF C 282 TXE QFS C 282 TXE QIG C 282 TXE QP C 282 TXE Q
61. 69 Thread Suspension 69 Semaphore Control Block TX SEMAPHORE 70 Deadly Embrace 70 Priority Inversion 72 m Mutexes 72 Mutex Mutual Exclusion 73 Creating Mutexes 73 Thread Suspension 73 Mutex Control Block TX MUTEX 74 Deadly Embrace 74 Priority Inversion 74 m Event Flags 75 Creating Event Flag Groups 76 Express Logic Inc ThreadX Thread Suspension 76 Event Flag Group Control Block TX EVENT FLAGS GROUP 76 Memory Block Pools 77 Creating Memory Block Pools 77 Memory Block Size 78 Pool Capacity 78 Pool s Memory Area 78 Thread Suspension 78 Memory Block Pool Control Block TX BLOCK POOL 79 Overwriting Memory Blocks 79 m Memory Byte Pools 79 Creating Memory Byte Pools 80 Pool Capacity 80 Pool s Memory Area 81 Thread Suspension 81 Memory Byte Pool Control Block TX BYTE POOL 82 Un deterministic Behavior 82 Overwriting Memory Blocks 82 m Application Timers 83 Timer Intervals 83 Timer Accuracy 84 Timer Execution 84 Creating Application Timers 84 Application Timer Control Block TX TIMER 84 Excessive Timers 85 Relative Time 85 Interrupts 85 TETEN User Guide Interrupt Control 86 ThreadX Managed Interrupts 86 ISR Template 87 High Frequency Interrupts 88 Interrupt Latency 88 Contents 7 4 Description of ThreadX Services 89 5 I O Drivers for ThreadX 223 lt O Driver Introduction 224 m Driver Functions 224 Driver Initialization 225 Driver Control
62. 79 m Memory Byte Pools 79 Creating Memory Byte Pools 80 Pool Capacity 80 Pool s Memory Area 81 Thread Suspension 81 Memory Byte Pool Control Block TX BYTE POOL 82 Un deterministic Behavior 82 Overwriting Memory Blocks 82 m Application Timers 83 Timer Intervals 83 Timer Accuracy 84 Timer Execution 84 Creating Application Timers 84 Application Timer Control Block TX TIMER 84 Excessive Timers 85 Relative Time 85 lt Interrupts 85 Interrupt Control 86 ThreadX Managed Interrupts 86 ISR Template 87 High Frequency Interrupts 88 Interrupt Latency 88 Express Logic Inc 44 Functional Components of ThreadX Execution Overview Initialization Thread Execution Interrupt Service Routines ISR There are four types of program execution within a ThreadX application Initialization Thread Execution Interrupt Service Routines ISRs and Application Timers Figure 2 on page 45 shows each different type of program execution More detailed information about each of these types is found in subsequent sections of this chapter As the name implies this is the first type of program execution in a ThreadX application Initialization includes all program execution between processor reset and the entry point of the thread scheduling loop After initialization is complete ThreadX enters its thread scheduling loop The scheduling loop looks for an application thread ready for execution When a ready thread is
63. 8 Event Flag Services 299 Interrupt Control 299 Message Queue Services 299 Semaphore Services 300 Mutex Services 300 Thread Control Services 301 Time Services 301 Timer Services 301 B ThreadX Constants 303 Alphabetic Listings 304 Listing by Value 306 C ThreadX Data Types 309 D ThreadX Source Files 315 m ThreadX C Include Files 316 m ThreadX C Source Files 316 m ThreadX Port Assembly Language Files 322 E ASCII Character Codes 323 ASCII Character Codes in HEX 324 Index 325 Express Logic Inc 14 TETEN User Guide ThreadX Figures Figure 1 Figure 2 Figure 3 Figure 4 Figure 5 Figure 6 Figure 7 Figure 8 Figure 9 Figure 10 Figure 11 Figure 12 Figure 13 Figure 14 Figure 15 Figure 16 Template for Application Development 36 Types of Program Execution 45 Memory Area Example 47 Initialization Process 51 Thread State Transition 53 Typical Thread Stack 60 Stack Preset to OXEFEF 61 Example of Suspended Threads 71 Simple Driver Initialization 228 Simple Driver Input 229 Simple Driver Output 230 Logic for Circular Input Buffer 232 Logic for Circular Output Buffer 233 Buffer 234 Input Output Lists 236 ThreadX File Header Example 265 TETEN User Guide 16 TETEN User Guide ThreadX About This Guide This guide provides comprehensive information about ThreadX the high performance real time kernel from Express Logic Inc It is intended for the embedded real time s
64. 9 140 141 142 143 Distribution file demo c Allocate the stack for thread 0 tx byte allocate amp byte pool 0 amp pointer DEMO STACK SIZE TX NO WAIT Create the main thread tx thread create amp thread 0 thread 0 thread 0 entry 0 pointer DEMO STACK SIZE 1 1 TX NO TIME SLICE TX AUTO START Allocate the stack for thread 1 tx byte allocate amp byte pool 0 amp pointer DEMO STACK SIZE TX NO WAIT Create threads 1 and 2 These threads pass information through a ThreadX message queue It is also interesting to note that these threads have a time slice tx thread create amp thread 1 thread 1 thread 1 entry 1 pointer DEMO STACK SIZE 16 16 4 TX AUTO START Allocate the stack for thread 2 tx byte allocate amp byte pool 0 amp pointer DEMO STACK SIZE TX NO WAIT tx thread create amp thread 2 thread 2 thread 2 entry 2 pointer DEMO STACK SIZE 16 16 4 TX AUTO START Allocate the stack for thread 3 tx byte allocate amp byte pool 0 amp pointer DEMO STACK SIZE TX NO WAIT Create threads 3 and 4 These threads compete for a ThreadX counting semaphore An interesting thing here is that both threads share the same instruction area tx thread create amp thread 3 thread 3 thread 3 and 4 entry 3 pointer DEMO STACK SIZE 8 8 TX NO TIME SLICE TX AUTO START Allocate the stack for thread 4 tx byte allocate amp byte pool 0 a
65. API service This file contains tx thread resume api which is responsible for processing application resume thread requests This file contains tx thread relinquish which is responsible for placing the current thread behind all other threads of the same priority that are ready for execution This file contains tx thread schedule which is responsible for scheduling and restoring the last context of the highest priority thread ready for execution This function is processor compiler specific and is written in assembly language This file contains tx thread suspend api which is responsible for processing application thread suspend requests Express Logic Inc 272 TX TSB S ASM TX TSE C TX TSLE C TX TSR S ASM TX TSUS C TX TT C Internal Composition of ThreadX This file contains tx thread stack build which is responsible for creating each thread s initial stack frame The initial stack frame causes an interrupt context return to the beginning of the tx thread shell entry function This function then calls the specified application thread entry function The tx thread stack build function is processor compiler specific and is written in assembly language This file contains tx thread shell entry which is responsible for calling the specified application thread entry function If the thread entry function returns tx thread shell entry suspends the thread in the finished state
66. D ERROR 0x0E Invalid thread control pointer TX PTR ERROR 0x03 Invalid pointer NULL for any destination pointer Allowed From Initialization threads timers and ISRs Preemption Possible No Example TX THREAD my thread CHAR name UINT state ULONG run count UINT priority UINT preemption threshold UINT time slice TX THREAD next thread TX THREAD suspended thread UINT status Retrieve information about a the previously created thread my thread Status tx thread info get amp my thread amp name amp state amp run count amp priority amp preemption threshold amp time slice amp next thread amp suspended thread If status equals TX SUCCESS the information requested is valid Express Logic Inc 186 Description of ThreadX Services See Also tx thread create tx thread delete tx thread identify tx thread preemption change tx thread priority change tx thread relinquish tx thread resume tx thread sleep tx thread suspend tx thread terminate tx thread time slice change tx thread wait abort TID User Guide Thread Control 187 Express Logic Inc 188 Description of ThreadX Services tx thread preemption change Change preemption threshold of application thread Prototype UINT tx thread preemption change TX THREAD thread ptr UINT new threshold UINT old threshold Description This service changes the preemptio
67. EFI C 289 TX EFIG C 289 TX EFS C 289 TXE EFC C 289 TXE EFD C 290 TXE EFG C 290 TXE EFIG C 290 TXE EFS C 290 m Block Memory Component 290 TX BLO H 290 TX BA C 291 TX BPC C 291 TX BPCLE C 291 TX BPD C 291 TX BPI C 291 TX BPIG C 291 TX BPP C 292 TX BR C 292 TXE BA C 292 TXE BPC C 292 TXE BPD C 292 TXE BPIG C 292 TXE BPP C 292 TXE BR C 292 m Byte Memory Component 293 TX BYT H 293 TX BYTA C 293 TX BYTC C 293 TX BYTCL C 294 TX BYTD C 294 TX BYTI C 294 TX BYTIG C 294 TX BYTPP C 294 TX BYTR C 294 TX BYTS C 294 TXE BTYA C 295 TXE BYTC C 295 TXE BYTD C 295 TXE BYTG C 295 TXE BYTP C 295 TXE BYTR C 295 Express Logic Inc 256 Internal Composition of ThreadX ThreadX Design Goals Simplicity Scalability High Performance ThreadX has three principal design goals simplicity scalability in size and high performance In many situations these goals are complementary i e simpler smaller software usually gives better performance Simplicity is the most important design goal of ThreadX It makes ThreadX easy to use test and verify In addition it makes it easy for developers to understand exactly what is happening inside This takes the mystery out of multi threading which contrasts sharply with the black box approach so prevalent in the industry ThreadX is also designed to be scalable Its instruction area size ranges from 2KBytes through 15Kbytes depending on the services actually used
68. FFFFFFFF Determines if the timer is automatically activated during creation If this value is TX_AUTO_ACTIVATE 0x01 the timer is made active Otherwise if the value TX_NO_ACTIVATE 0x00 is selected the timer is created in a non active state In this case a subsequent tx_timer_activate service call is necessary to get the timer actually started Application Timers 215 Return Values TX SUCCESS 0x00 Successful application timer creation TX TIMER ERROR 0x15 Invalid application timer pointer Either the pointer is NULL or the timer is already created TX TICK ERROR 0x16 Invalid value a zero supplied for initial ticks TX ACTIVATE ERROR 0x17 Invalid activation selected TX CALLER ERROR 0x13 Invalid caller of this service Allowed From Initialization and threads Preemption Possible No Example TX TIMER my timer UINT status Create an application timer that executes my timer function after 100 ticks initially and then after every 25 ticks This timer is specified to start immediately Status tx timer create amp my timer my timer name my timer function 0x1234 100 25 TX AUTO ACTIVATE If status equals TX SUCCESS my timer function will be called 100 timer ticks later and then called every 25 timer ticks Note that the value 0x1234 is passed to my timer function every time it is called See Also tx timer activate tx timer change tx timer deactivate tx timer delete tx t
69. G tx byte pool fragments CHAR PTR tx byte pool list CHAR PTR tx byte pool search CHAR PTR tx byte pool start ULONG tx byte pool size struct TX THREAD STRUCT tx byte pool owner struct TX THREAD STRUCT tx byte pool suspension list ULONG tx byte pool suspended count struct TX BYTE POOL STRUCT tx byte pool created next tx byte pool created previous TX BYTE POOL TETTES User Guide 313 typedef struct TX MUTEX STRUCT ULONG tx_mutex_id CHAR PTR tx_mutex_name ULONG tx mutex ownership count TX THREAD tx mutex owner UINT tx mutex inherit UINT tx mutex original priority UINT tx mutex original threshold struct TX THREAD STRUCT tx mutex suspension list ULONG tx mutex suspended count struct TX MUTEX STRUCT tx mutex created next tx mutex created previous TX MUTEX Express Logic Inc 314 ThreadX Data Types TID User Guide APPENDIXD ThreadX Source Files m ThreadX C Include Files 316 m ThreadX C Source Files 316 m ThreadX Port Assembly Language Files 322 ERIS gt User Guide 316 ThreadX Source Files ThreadX C Include Files TX API H TX BLO H TX BYT H TX EVE H TX INI H TX MUT H TX PORT H TX QUE H TX THR H TX TIM H TX SEM H Application Interface Include Block Memory Component Include Byte Memory Component Include Event Flag Component Include Initialize Component Include Mutex Component Include Port Sp
70. HAR PTR tx_queue_name UINT tx queue message size ULONG tx queue capacity ULONG tx queue enqueued ULONG tx queue available storage ULONG PTR tx queue start ULONG PTR tx queue end ULONG PTR tx queue read ULONG PTR tx queue write struct TX THREAD STRUCT tx queue suspension list ULONG tx queue suspended count Struct TX QUEUE STRUCT tx queue created next tx queue created previous TX QUEUE TETTES User Guide 311 typedef struct TX THREAD STRUCT LONG tx_thread_id LONG tx_run_count TR tx stack ptr TR tx stack start PTR tx_stack_end LONG tx_stack_size LONG tx_time_slice LONG tx_new_time_slice struct TX THREAD STRUCT tx ready next tx ready previous Sp on q S lt H HH o o o er TX THREAD PORT EXTENSION See tx port h for details CHAR PTR tx thread name UINT tx priority UINT tx state UINT tx delayed suspend UINT tx suspending UINT tx preempt threshold ULONG tx priority bit VOID tx thread entry ULONG ULONG tx entry parameter TX INTERNAL TIMER tx thread timer VOID tx suspend cleanup struct TX THREAD STRUCT VOID PTR tx suspend control block struct TX THREAD STRUCT tx suspended next tx suspended previous ULONG tx suspend info VOID PTR tx additional suspend info UINT tx suspend option UINT tx suspend status struct TX THREAD STRUCT tx created next tx created previous VOID PTR t
71. Hills MULTI tools The ThreadX demonstration should not have any stack size problems assuming no modifications have been made If the system crash persists disable all interrupt sources The ThreadX periodic timer interrupt is typically setup in tx ill Express Logic Inc 38 D i Installation and Use of ThreadX If this solves the problem the system stack setup by MULTI might be too small or application ISRs don t conform to the format specified in readme txt Determine how far the system runs and contact Express Logic support with the information gathered See the readme txt file supplied with the distribution for more specific details regarding the demonstration system and specific hardware issues to be aware of Configuration Options i There are several configuration options available for ThreadX using the Green Hills MULTI tools as follows TX DISABLE ERROR CHECKING This conditional compilation flag is used to bypass service call error checking If the condition compilation flag is defined within an application C file all basic parameter error checking is disabled This option is used to improve performance by as much as 3096 However this should only be used after the application is thoroughly debugged ThreadX API return values NOT affected by disabling error checking are listed in bold in the Return Values section of the API description in Chapter 4 The non bold return values are vo
72. Message queue control blocks can also be located anywhere in memory but it is most common to make Express Logic Inc 68 Message Destination Pitfall N Functional Components of ThreadX the control block a global structure by defining it outside the scope of any function As mentioned previously messages are copied between the queue area and application data areas It is very important to insure that the destination for a received message is large enough to hold the entire message If not the memory following the message destination will likely be corrupted This is especially lethal when a too small message destination is on the stack nothing like corrupting the return address of a function Counting Semaphores Mutual Exclusion ThreadX provides 32 bit counting semaphores that range in value between 0 and 4 294 967 295 There are two operations for counting semaphores tx_semaphore_get and tx_semaphore_put The get operation decreases the semaphore by one If the semaphore is 0 the get operation is not successful The inverse of the get operation is the put operation It increases the semaphore by one Each counting semaphore is a public resource ThreadX places no constraints on how counting semaphores are used Counting semaphores are typically used for mutual exclusion However counting semaphores can also be used as a method for event notification Mutual exclusion pertains to controlling the access
73. O drivers for ThreadX The information presented in this chapter is designed to help developers write application specific drivers The following lists the I O driver topics covered in this chapter O Driver Introduction 224 m Driver Functions 224 Driver Initialization 225 Driver Control 225 Driver Access 225 Driver Input 225 Driver Output 225 Driver Interrupts 226 Driver Status 226 Driver Termination 226 m Simple Driver Example 226 Simple Driver Initialization 226 Simple Driver Input 228 Simple Driver Output 229 Simple Driver Shortcomings 230 m Advanced Driver Issues 231 I O Buffering 231 Circular Byte Buffers 231 Circular Buffer Input 231 Circular Output Buffer 233 Buffer I O Management 234 TX IO BUFFER 234 Buffered I O Advantage 235 Buffered Driver Responsibilities 235 Interrupt Management 237 Thread Suspension 237 ERES User Guide 224 IIO Drivers for ThreadX I O Driver Introduction Communication with the external environment is an important component of most embedded applications This communication is accomplished through hardware devices that are accessible to the embedded application software The software components responsible for managing such devices are commonly called O Drivers I O drivers in embedded real time systems are inherently application dependent This is true for two principal reasons the vast diversity of target hardware and the equally vast performance requirements impos
74. PRI C 288 TXE QC C 282 TXE QD C 282 TXE QF C 282 TXE QFS C 282 TXE QIG C 282 TXE QP C 282 TXE QR C 282 TXE QS C 283 TXE SC C 284 287 TXE SD C 285 TXE SG C 285 287 TXE SIG C 285 TXE SP C 285 288 TXE SPRI C 285 TXE TAA C 279 TXE TC C 273 TXE TDA C 279 TXE TDEL C 273 TXE TIG C 273 TXE TIMD C 279 TXE TIMI C 279 TXE TMCH C 280 TXE TMCR C 280 TXE TPCH C 273 TXE TRA C 274 TXE TREL C 274 TXE TRPC C 274 TETEN User Guide TXE TSA C 274 TXE TT C 274 TXE TTSC C 274 TXE TWA C 274 types of program execution 44 typical thread stack 60 U UART 231 UINT 263 ULONG 263 un deterministic 57 77 un deterministic behavior 82 un deterministic priority inversion 63 75 uninitialized data 46 48 unnecessary processing 26 unpredictable behavior 50 user supplied main function 49 using ThreadX 33 V version ID 40 VOID 263 W watchdog services 46 x x_kernel_enter 34
75. R C 282 TXE QS C 283 m Semaphore Component 283 TX SEM H 283 TETEN User Guide Contents 11 TX SC C 283 TX SCLE C 284 TX SD C 284 TX SG C 284 TX SI C 284 TX SIG C 284 TX SP C 284 TX SPRI C 284 TXE SC C 284 TXE SD C 285 TXE SG C 285 TXE SIG C 285 TXE SP C 285 TXE SPRI C 285 m Mutex Component 285 TX MUT H 285 TX MC C 286 TX MCLE C 286 TX MD C 286 TX MG C 286 TX MI C 286 TX MIG C 287 TX MP C 287 TX MPC C 287 TX MPRI C 287 TXE MC C 287 TXE MD C 287 TXE MG C 287 TXE MIG C 287 TXE MP C 288 TXE MPRI C 288 m Event Flag Component 288 TX EVE H 288 TX EFC C 289 TX EFCLE C 289 TX EFD C 289 TX EFG C 289 TX EFI C 289 TX EFIG C 289 TX EFS C 289 TXE EFC C 289 Express Logic Inc 12 ThreadX TXE EFD C 290 TXE EFG C 290 TXE EFIG C 290 TXE EFS C 290 Block Memory Component 290 TX BLO H 290 TX BA C 291 TX BPC C 291 TX BPCLE C 291 TX BPD C 291 TX BPI C 291 TX BPIG C 291 TX BPP C 292 TX BR C 292 TXE BA C 292 TXE BPC C 292 TXE BPD C 292 TXE BPIG C 292 TXE BPP C 292 TXE BR C 292 m Byte Memory Component 293 TETEN User Guide TX BYT H 293 TX BYTA C 293 TX BYTC C 293 TX BYTCL C 294 TX BYTD C 294 TX BYTI C 294 TX BYTIG C 294 TX BYTPP C 294 TX BYTR C 294 TX BYTS C 294 TXE BTYA C 295 TXE BYTC C 295 TXE BYTD C 295 TXE BYTG C 295 TXE BYTP C 295 TXE BYTR C 295 Contents 13 A ThreadX API Services 297 Entry Function 298 Byte Memory Services 298 Block Memory Services 29
76. ROR 0x0005 TX SLEEP 4 TX START ERROR 0x0010 TX SUCCESS 0x0000 TX SUSPEND ERROR 0x0014 TX SUSPEND LIFTED 0x0019 TX SUSPENDED 3 TX TCP IP 12 TX TERMINATED 2 TX THREAD ERROR 0x000E Express Logic Inc 306 Listing by Value ThreadX Constants TX THRESH ERROR TX TICK ERROR TX TIMER ERROR TX TRUE 0x0018 0x0016 0x0015 1 TX WAIT ABORT ERROR 0x001B TX WAIT ABORTED TX WAIT ERROR TX WAIT FOREVER TX DONT START TX FALSE TX NO ACTIVATE TX NO INHERIT TX NO TIME SLICE TX NO WAIT TX NULL TX OR TX READY TX SUCCESS TX 1 ULONG TX AUTO ACTIVATE TX AUTO START TX COMPLETED TX FOREVER TX DELETED TX INHERIT TX OR CLEAR TX TRUE TX 2 ULONG TX AND el gt User Guide 0x001A 0x0004 FFFFFFFF O 0 O 0 0001 1 N N TX POOL ERROR TX TERMINATED TX AND CLEAR TX PTR ERROR TX SUSPENDED TX 4 ULONG TX SLEEP TX WAIT ERROR TX QUEUE SUSP TX SIZE ERROR TX GROUP ERROR TX SEMAPHORE SUSP TX EVENT FLAG TX NO EVENTS TX 8 ULONG TX BLOCK MEMORY TX OPTION ERROR TX BYTE MEMORY TX QUEUE ERROR TX IO DRIVER TX QUEUE EMPTY TX FILE TX QUEUE FULL TX SEMAPHORE ERROR TX TCP IP TX MUTEX SUSP TX NO INSTANCE TX THREAD ERROR TX PRIORITY ERROR TX 16 ULONG TX START ERROR 307 0x0002 2 3 0x0003 3 4 4 0x0004 5 0x0005 0x0006 6 7 0x0007 8 8 0x0008 9 0x0009 10 0x000A 11 0x000B 0x000C 12 13 0x000D 0x000E 0x000F 16 0x0010 Expres
77. TMCH C This file contains txe timer change which is responsible for checking application timer change requests for errors TXE TMCR C This file contains txe timer create which is responsible for checking application timer create requests for errors Queue Component This component is responsible for all queue management activities including queue creation deletion and message sending receiving TX QUE H This is the specification file for the ThreadX Queue Component All component constants external interfaces and data structures are defined in this file The global data for the queue component is defined in this file and consists of the following data elements tx queue created ptr This TX QUEUE pointer is the head pointer of the created queue list The list is a doubly linked circular list of all created queue control blocks tx queue created count This ULONG represents the number of created application queues TX QC C This file contains tx queue create which is responsible for processing queue create requests ERIS User Guide TX QCLE C TX QD C TX QF C TX QFS C TX QI C TX QIG C TX QP C TX QR C Queue Component 281 This file contains tx queue cleanup which is responsible for processing queue suspension time outs queue suspended thread termination and thread wait abort requests This file contains tx queue delete which is responsible for processing queue deletion requests
78. TX QF C TX QFS C TX QI C TX QIG C TX QP C TX QR C TX QS C TXE QC C TXE QD C TXE QF C TXE QFS C TXE QIG C TXE QP C TXE QR C TXE QS C TX TA C TX TAA C TX TD C TX TDA C TX TIMCH C TX TIMCR C TX TIMD C TX TIMI C TX TIMIG C TX TTE C TXE TAA C TXE TMCH C Queue Create Queue Cleanup Queue Delete Queue Flush Queue Front Send Queue Initialize Queue Information Get Queue Prioritize Queue Receive Queue Send Queue Create Error Checking Queue Delete Error Checking Queue Flush Error Checking Queue Front Send Error Checking Queue Information Get Error Checking Queue Prioritize Error Checking Queue Receive Error Checking Queue Send Error Checking Timer Activate Timer Activate API Timer Deactivate Timer Deactivate API Timer Change Timer Create Timer Delete Timer Initialize Timer Information Get Timer Thread Entry Timer Activate API Error Checking Timer Change Error Checking Express Logic Inc 320 ThreadX Source Files TXE TMCR C TXE TDA C TXE TIMD C TXE TIMI C TX TIMEG C TX TIMES C TX TC C TX TDEL C TX TI C TX TIDE C TX TIG C TX TPCH C TX TPRCH C TX TR C TX TRA C TX TREL C TX TSA C TX TSE C TX TSLE C TX TSUS C TX TT C TX TTO C TX TTS C TX TTSC C TX TWA C TXE TC C TXE TDEL C TXE TIG C TXE TPCH C Timer Create Error Checking Timer Deactivate API Error Checking Timer Delete Error Checking Timer Information Get Error Checking Time Get Time Set Th
79. Timers Application Timer Control Block TX TIMER Functional Components of ThreadX Timer expirations are specified in terms of ticks The specified expiration value is decreased by one on each timer tick Since an application timer could be enabled just prior to a timer interrupt or timer tick the actual expiration time could be up to one tick early If the timer tick rate is 10ms application timers may expire up to 10ms early This is more significant for 10ms timers than 1 second timers Of course increasing the timer interrupt frequency decreases this margin of error Application timers execute in the order they become active For example if three timers are created with the same expiration value and activated their corresponding expiration functions are guaranteed to execute in order they were activated Application timers are created either during initialization or during run time by application threads There are no limits on the number of application timers in an application The characteristics of each application timer are found in its control block It contains useful information such as the 32 bit expiration identification value This structure is defined in the tx api h file Application timer control blocks can be located anywhere in memory but it is most common to make the control block a global structure by defining it outside the scope of any function ERIS User Guide Excessive Timers Relat
80. Values TX SUCCESS TX POOL ERROR TX PTR ERROR ERIS User Guide Pointer to previously created memory block pool Pointer to destination for the pointer to the block pool s name Pointer to destination for the number of available blocks in the block pool Pointer to destination for the total number of blocks in the block pool Pointer to destination for the pointer to the thread that is first on the suspension list of this block pool Pointer to destination for the number of threads currently suspended on this block pool Pointer to destination for the pointer of the next created block pool 0x00 Successful block pool information retrieve 0x02 Invalid memory block pool pointer 0x03 Invalid pointer NULL for any destination pointer Memory Blocks 101 Allowed From Initialization threads timers and ISRs Preemption Possible No Example TX BLOCK POOL my pool CHAR name ULONG available ULONG total blocks TX THREAD first suspended ULONG suspended count TX BLOCK POOL next pool UINT status Retrieve information about a the previously created block pool my pool status tx block pool info get amp my pool amp name amp available amp total packets amp first suspended amp suspended count amp next pool If status equals TX SUCCESS the information requested is valid See Also tx block pool allocate tx block pool create tx block pool dele
81. X QUEUE ERROR 0x09 Invalid message queue pointer Either the pointer is NULL or the queue is already created TX PTR ERROR 0x03 Invalid starting address of the message queue TX SIZE ERROR 0x05 Size of message queue is invalid TX CALLER ERROR 0x13 Invalid caller of this service Allowed From Initialization and threads Preemption Possible No Example TX QUEUE my queue UINT status Create a message queue whose total size is 2000 bytes Starting at address 0x300000 Each message in this queue is defined to be 4 32 bit words long Status tx queue create amp my queue my queue name TX 4 ULONG VOID 0x300000 2000 status equals my queue contains room If stat ls TX SUCCESS 1 for storing 125 messages 2000 bytes 16 bytes per message See Also tx queue delete tx queue flush tx queue front send tx queue info get tx queue prioritize tx queue receive tx queue send Express Logic Inc 148 Description of ThreadX Services tx queue delete Delete a message queue Prototype UINT tx queue delete TX QUEUE queue ptr Description This service deletes the specified message queue All threads suspended waiting for a message from this queue are resumed and given a TX DELETED return status associated with the queue which is available after this service completes In addition the application must prevent use of a deleted queue It is the application s responsibil
82. a TX DELETED return status The application must prevent use of a deleted event flag group Input Parameters group ptr Pointer to a previously created event flags group Return Values TX SUCCESS 0x00 Successful event flag group deletion TX GROUP ERROR 0x06 Invalid event flag group pointer TX CALLER ERROR 0x13 Invalid caller of this service Allowed From Threads Preemption Possible Yes ELITSE gt User Guide Event Flags 123 Example TX EVENT FLAGS GROUP my event flag group UINT status Delete event flag group Assume that the group has already been created with a call to tx event flags create Status tx event flags delete amp my event flags group If status equals TX SUCCESS the event flags group is deleted See Also tx event flags create tx event flags get tx event flags info get tx event flags set Express Logic Inc 124 Description of ThreadX Services tx event flags get Get event flags from event flag group Prototype UINT tx event flags get TX EVENT FLAGS GROUP group ptr LONG requested flags UINT get option ULONG actual flags ptr ULONG wait option d Description This service retrieves event flags from the specified event flag group Each event flag group contains 32 event flags Each flag is represented by a single bit This service can retrieve a variety of event flag combinations as selected by the input parameters Input Par
83. age Queue Capacity Queue Memory Area Functional Components of ThreadX Message queues are created either during initialization or during run time by application threads There are no limits on the number of message queues in an application Each message queue supports a number of fixed sized messages The available message sizes are 1 2 4 8 and 16 32 bit words The message size is specified when the queue is created Application messages greater than 16 words must be passed by pointer This is accomplished by creating a queue with a message size of 1 word enough to hold a pointer and then sending and receiving message pointers instead of the entire message The number of messages a queue can hold is a function of its message size and the size of the memory area supplied during creation The total message capacity of the queue is calculated by dividing the number of bytes in each message into the total number of bytes in the supplied memory area For example if a message queue that supports a message size of 1 32 bit word 4 bytes is created with a 100 byte memory area its capacity is 25 messages As mentioned before the memory area for buffering messages is specified during queue creation Like other memory areas in ThreadX it can be located anywhere in the target s address space This is an important feature because it gives the application considerable flexibility For example an application might locate the m
84. ains txe thread info get which is responsible for checking thread information get requests for errors This file contains txe thread preemption change which is responsible for checking preemption change requests for errors Express Logic Inc 274 TXE TRA C TXE TREL C TXE TRPC C TXE TSA C TXE TT C TXE TTSC C TXE TWA C Internal Composition of ThreadX This file contains txe thread resume api which is responsible for checking thread resume requests for errors This file contains txe thread relinquish which is responsible for checking thread relinquish requests for errors This file contains txe thread priority change which is responsible for checking priority change requests for errors This file contains txe thread suspend api which is responsible for checking thread suspend requests for errors This file contains txe thread terminate which is responsible for checking thread terminate requests for errors This file contains txe thread time slice change which is responsible for checking time slice changes for errors This file contains txe thread wait abort which is responsible for checking thread wait abort requests for errors ERIS User Guide Timer Component 275 Timer Component TX TIM H This component is responsible for all timer management activities including thread time slicing thread sleeps API service time outs and application timers The timer compo
85. akes it much easier to repair or enhance an application that utilizes ThreadX A possible work around to the control loop response time problem is to add more polling This improves the responsiveness but still doesn t guarantee a constant worst case response time and does nothing to enhance future modification of the application Also the processor is now performing even more unnecessary processing because of the extra polling All of this unnecessary processing reduces the overall throughput of the system An interesting point regarding overhead is that many developers assume that multi threaded environments like ThreadX increase overhead and have a negative impact on total system throughput But in some cases multi threading actually reduces overhead by eliminating all of the redundant polling that occurs in control loop environments The overhead associated with multi threaded kernels is typically a function of the time required for context switching If the context switch time is less than the polling process ThreadX provides a solution with the potential of less overhead and more throughput This makes ThreadX an obvious choice for applications that have any degree of complexity or size ThreadX provides a robust processor independent interface between the application and the underlying processor This allows developers to concentrate on the application rather than spending a significant amount of time learning hardware details
86. alid message queue pointer TX CALLER ERROR 0x13 Invalid caller of this service Allowed From Initialization threads timers and ISRs Preemption Possible Yes ELITSE gt User Guide Message Queues 151 Example TX QUEUE my queue UINT status Flush out all pending messages in the specified message queue Assume that the queue has already been created with a call to tx queue create Status tx queue flush amp my queue If status equals TX SUCCESS the message queue is empty See Also tx queue create tx queue delete tx queue front send tx queue info get tx queue prioritize tx queue receive tx queue send Express Logic Inc 152 Description of ThreadX Services tx queue front send Send a message to the front of queue Prototype UINT tx queue front send TX QUEUE queue ptr VOID source ptr ULONG wait option Description This service sends a message to the front location of the specified message queue The message is copied to the front of the queue from the memory area specified by the source pointer Input Parameters queue ptr Pointer to a message queue control block source ptr Pointer to the message wait option Defines how the service behaves if the message queue is full The wait options are defined as follows TX NO WAIT 0x00000000 TX WAIT FOREVER OxFFFFFFFF timeout value 0x00000001 through OxFFFFFFFE Selecting TX NO WAIT results in an immediate re
87. ameters group ptr Pointer to a previously created event flag group requested flags 32 bit unsigned variable that represents the requested event flags get option Specifies whether all or any of the requested event flagsare required The following are valid selections TX AND 0x02 TX AND CLEAR 0x03 TX OR 0x00 TX OR CLEAR 0x01 Selecting TX AND or TX AND CLEAR specifies that all event flags must be present in the group Selecting TX OR or TX OR CLEAR specifies that any event flag is satisfactory Event flags that satisfy the request are cleared set to zero if TX AND CLEAR or TX OR CLEAR are specified actual flags ptr Pointer to destination of where the retrieved event flags are placed Note that the actual flags obtained may contain flags that were not requested ERIS User Guide Event Flags 125 wait option Return Values TX SUCCESS TX DELETED TX NO EVENTS TX WAIT ABORTED TX GROUP ERROR TX PTR ERROR TX WAIT ERROR TX OPTION ERROR Defines how the service behaves if the selected event flags are not set The wait options are defined as follows TX NO WAIT 0x00000000 TX WAIT FOREVER OxFFFFFFFF timeout value 0x00000001 through OxFFFFFFFE Selecting TX NO WAIT results in an immediate return from this service regardless of whether or not it was successful This is the only valid option if the service is called from a non thread e g Initialization timer or ISR Selecting TX WAIT FOREVER
88. ases the run time environment simply assumes there is enough stack space This causes thread execution to corrupt memory adjacent usually before its stack area The results are very unpredictable but most often result in an un natural Express Logic Inc 62 Reentrancy Thread Priority Pitfalls Functional Components of ThreadX change in the program counter This is often called jumping into the weeds Of course the only way to prevent this is to ensure that all thread stacks are large enough One of the real beauties of multi threading is that the same C function can be called from multiple threads This provides great power and also helps reduce code space However it does require that C functions called from multiple threads are reentrant What does reentrant mean Basically a reentrant function stores the caller s return address on the current stack and does not rely on global or static C variables that it previously setup Most compilers place the return address on the stack Hence application developers must only worry about the use of globals and statics An example of a non reentrant function is the string token function strtok found in the standard C library This function remembers the previous string pointer on subsequent calls It does this with a static string pointer If this function is called from multiple threads it would most likely return an invalid pointer Selecting thread priorities is o
89. aves if there are no memory blocks available The wait options are defined as follows TX NO WAIT 0x00000000 TX WAIT FOREVER OxFFFFFFFF timeout value 0x00000001 through OxFFFFFFFE Selecting TX NO WAIT results in an immediate return from this service regardless of whether or not it was successful This is the only valid option if the service is called from a non thread e g Initialization timer or ISR Selecting TX WAIT FOREVER causes the calling thread to suspend indefinitely until a memory block is available Selecting a numeric value 1 OxFFFFFFFE specifies the maximum number of timer ticks to stay suspended while waiting for a memory block ERIS User Guide Memory Blocks 95 Return Values TX SUCCESS 0x00 Successful memory block allocation TX DELETED 0x01 Memory block pool was deleted while thread was suspended TX NO MEMORY 0x10 Service was unable to allocate a block of memory TX WAIT ABORTED 0x1A Suspension was aborted by another thread timer or ISR TX POOL ERROR 0x02 Invalid memory block pool pointer TX PTR ERROR 0x03 Invalid pointer to destination pointer TX WAIT ERROR 0x04 A wait option other than TX NO WAIT was specified on a call from a non thread Allowed From Initialization threads timers and ISRs Preemption Possible Yes Example TX BLOCK POOL my pool unsigned char memory ptr UINT status Allocate a memory block from my pool Assume that the p
90. bution disk depends on the target processor and the ThreadX package purchased Following is a list of several important files that are common to most product distributions readme txt This file contains specific information about the ThreadX port including information about the target processor and the Green Hills MULTI tools tx api h This C header file contains all system equates data structures and service prototypes tx port h This C header file contains all Green Hills MULTI specific data definitions and structures demo c This C file contains a small demo application Express Logic Inc 32 Installation and Use of ThreadX demo bld This Green Hills MULTI build file defines how to build the ThreadX demonstration demo el bld This Green Hills MULTI build file is the same as demo bld except that it enables event logging for the ThreadX demonstration Note that is requires the ThreadX library built by txe bld demo ld This linker control file specifies where the demo application resides in the target memory demo el Id This linker control file is the same as demo ld except it also allocates target memory for event logging tx bld This Green Hills MULTI build file defines how to build the ThreadX C library It is distributed with the premium package txe bld This Green Hills MULTI build file is the same as tx bld except that it enables event logging throughout the ThreadX C library It is also distr
91. by the application This enables ThreadX to support a wide range of microprocessor architectures ranging from small micro controllers through high performance RISC and DSP processors How is ThreadX so scalable First ThreadX is designed with a software component methodology which allows automatic removal of whole components that are not used Second it places each function in a separate file to minimize each function s interaction with the rest of the system Because ThreadX is implemented as a C library only the functions that are used become part of the final embedded image ThreadX is designed for high performance This is achieved in a variety of ways including algorithm optimizations register variables in line assembly ERIS User Guide ThreadX ANSI C Library System Include Files i ThreadX Design Goals 257 language low overhead timer interrupt handling and optimized context switching In addition applications have the ability with the conditional compilation flag TX DISABLE ERROR CHECKING to disable the basic error checking facilities of the ThreadX API This feature is very useful in the tuning phase of application development By disabling basic error checking a 30 percent performance boost can be achieved on most ThreadX implementations And of course the resulting code image is also smaller As mentioned before ThreadX is implemented as a C library which must be linked with the application
92. cause they could cause fatal errors About This Guide 19 ThreadX Data Types In addition to the custom ThreadX control structure data types there are a series of special data types that are used in ThreadX service call interfaces These special data types map directly to data types of the underlying C compiler This is done to insure portability between different C compilers The exact implementation can be found in the tx port h file included on the distribution disk The following is a list of ThreadX service call data types and their associated meanings UINT Basic unsigned integer This type must support 8 bit unsigned data however it is mapped to the most convenient unsigned data type which may support 16 or 32 bit signed data ULONG Unsigned long type This type must support 32 bit unsigned data VOID Almost always equivalent to the compiler s void type CHAR Most often a standard 8 bit character type Additional data types are used within the ThreadX source They are also located in the tx port h file Express Logic Inc 20 ThreadX Customer Support Center Support engineers 858 613 6640 Support fax 858 521 4259 Support email support expresslogic com Web page http www expresslogic com Where to Send The staff at Express Logic is always striving to Comments provide you with better products To help us achieve this goal email any comments and suggestions to the Customer Support Center a
93. cription of ThreadX Services tx thread info get Retrieve information about a thread Prototype UINT tx thread info get THREAD thread ptr CHAR name UINT state ULONG run count UINT priority UINT preemption threshold ULONG time slice TX THREAD next thread TX THREAD suspended thread Description This service retrieves information about the specified thread Input Parameters thread ptr Pointer to thread control block name Pointer to destination for the pointer to the thread s name state Pointer to destination for the thread s current execution state Possible values are as follows TX READY 0x00 TX COMPLETED 0x01 TX TERMINATED 0x02 TX SUSPENDED 0x03 TX SLEEP 0x04 TX QUEUE SUSP 0x05 TX SEMAPHORE SUSP 0x06 TX EVENT FLAG 0x07 TX BLOCK MEMORY 0x08 TX BYTE MEMORY 0x09 TX MUTEX SUSP 0 00 TX IO DRIVER 0x0A run_count Pointer to destination for the thread s run count priority Pointer to destination for the thread s priority preemption threshold Pointer to destination for the thread s preemption threshold time_slice Pointer to destination for the thread s time slice ERIS User Guide Thread Control 185 next thread Pointer to destination for next created thread pointer suspended thread Pointer to destination for pointer to next thread in suspension list Return Values TX SUCCESS 0x00 Successful thread information retrieval TX THREA
94. d states TX READY 0x00 TX COMPLETED 0x01 TX TERMINATED 0x02 TX SUSPENDED 0x03 TX SLEEP 0x04 TX QUEUE SUSP 0x05 TX SEMAPHORE SUSP 0x06 TX EVENT FLAG 0x07 TX BLOCK MEMORY 0x08 TX BYTE MEMORY 0x09 TX MUTEX SUSP 0 0 TX 10 DRIVER 0x0A Of course there are many other interesting fields in the thread control block including the stack pointer time slice value priorities etc The user is welcome to review any and all of the control block members but modification is strictly prohibited There is no equate for the executing state mentioned earlier in this section It is not necessary l since there is only one executing thread at a given time The state of an executing thread is also TX_READY ERIS User Guide Currently Executing Thread Thread Stack Area Thread Execution 59 As mentioned before there is only one thread executing at any given time There are several ways to identify the executing thread depending on who is making the request A program segment can get the control block address of the executing thread by calling tx thread identify This is useful in shared portions of application code that are executed from multiple threads In debug sessions users can examine the internal ThreadX pointer tx thread current ptr It contains the control block address of the currently executing thread If this pointer is NULL no application thread is executing i e ThreadX is waitin
95. def TX IO BUFFER consists of two pointers The tx next packet pointer is used to link multiple packets on either the input or output list The ERIS User Guide Buffered I O Advantage Buffered Driver Responsibilities Advanced Driver Issues 235 tx next buffer pointer is used to link together buffers that make up an individual packet of data from the device Both of these pointers are set to NULL when the buffer is allocated from the pool In addition some devices may require another field to indicate how much of the buffer area actually contains data What are the advantages of a buffer I O scheme The biggest advantage is that data is not copied between the device registers and the application s memory Instead the driver provides the device with a series of buffer pointers Physical device I O utilizes the supplied buffer memory directly Using the processor to copy input or output packets of information is extremely costly and should be avoided in any high throughput I O situation Another advantage to the buffered I O approach is that the input and output lists do not have full conditions All of the available buffers can be on either list at any one time This contrasts with the simple byte circular buffers presented earlier in the chapter Each had a fixed size determined at compilation Buffered I O drivers are only concerned with managing linked lists of I O buffers An input buffer list is maintained for packet
96. delete TX TIMER timer ptr UINT tx timer info get TX TIMER timer ptr CHAR name UINT active ULONG remaining ticks ULONG reschedule ticks TX TIMER next timer Express Logic Inc 302 ThreadX API Services TID User Guide ThreadX Constants m Alphabetic Listings 304 lt Listing by Value 306 ERIS a gt User Guide 304 Alphabetic Listings ThreadX Constants TX 1 ULONG TX 2 ULONG TX 4 ULONG TX 8 ULONG TX 16 ULONG TX ACTIVATE ERROR TX AND TX AUTO ACTIVATE TX AND CLEAR TX AUTO START TX BLOCK MEMORY TX BYTE MEMORY TX CALLER ERROR TX COMPLETED TX DELETE ERROR TX DELETED TX DONT START TX EVENT FLAG TX FALSE TX FILE TX FOREVER TX GROUP ERROR TX INHERIT TX INHERIT ERROR TX IO DRIVER TX MAX PRIORITIES TX MUTEX ERROR TX MUTEX SUSP TX NO ACTIVATE TX NO EVENTS TX NO INHERIT el gt User Guide F N 8 16 0x0017 Oo w N 0x0013 1 0x0011 0x0001 0 7 0 11 1 0x0006 1 0x001F 10 32 0x001F 13 0 0x0007 0 305 TX NO INSTANCE 0x000D TX NO MEMORY 0x0010 TX NO TIME SLICE 0 TX NO WAIT 0 TX NOT AVAILABLE 0x001D TX NOT OWNED 0x001E TX NULL 0 TX OPTION ERROR 0x0008 TX OR 0 TX OR CLEAR 1 TX POOL ERROR 0x0002 TX PRIORITY ERROR 0x000F TX PTR ERROR 0x0003 TX QUEUE EMPTY 0x000A TX QUEUE ERROR 0x0009 TX QUEUE FULL 0x000B TX QUEUE SUSP 5 TX READY 0 TX RESUME ERROR 0x0012 TX SEMAPHORE ERROR 0x000C TX SEMAPHORE SUSP 6 TX SIZE ER
97. djacent free memory blocks are merged together during a subsequent allocation search for a large enough free memory block This process is called de fragmentation Each memory byte pool is a public resource ThreadX places no constraints on how pools are used except that memory byte services can not be called from ISRs Memory byte pools are created either during initialization or during run time by application threads There are no limits on the number of memory byte pools in an application The number of allocatable bytes in a memory byte pool is slightly less than what was specified during creation This is because management of the free memory area introduces some overhead Each free memory block in the pool requires the equivalent of two C pointers of overhead In addition the pool is created with two blocks a large free block and a small permanently allocated block at the end of the memory area This allocated block is used to improve performance of the allocation algorithm It eliminates the need to continuously check for the end of the pool area during merging During run time the amount of overhead in the pool typically increases Allocations of an odd number of ERIS User Guide Pool s Memory Area Thread Suspension Memory Byte Pools 81 bytes are padded to insure proper alignment of the next memory block In addition overhead increases as the pool becomes more fragmented The memory area for a memory byte poo
98. ds can have the same priority as others in the application In addition thread priorities can be changed during run time ThreadX schedules threads based upon their priority The ready thread with the highest priority is executed first If multiple threads of the same priority are ready they are executed in a first in first out FIFO manner Round robin scheduling of multiple threads having the same priority is supported by ThreadX This is accomplished through cooperative calls to tx thread relinquish Calling this service gives all ERIS User Guide Time Slicing Preemption i Thread Execution 55 other ready threads at the same priority a chance to execute before the tx thread relinquish caller executes again Time slicing provides another form of round robin scheduling In ThreadX time slicing is available on a per thread basis The thread s time slice is assigned during creation and can be modified during run time What exactly is a time slice A time slice specifies the maximum number of timer ticks timer interrupts that a thread can execute without giving up the processor When a time slice expires all other ready threads of the same priority level are given a chance to execute before the time sliced thread executes again A fresh thread time slice is given to a thread after it suspends relinquishes makes a ThreadX service call that causes preemption or is itself time sliced When a time sliced thread
99. e Prototype UINT tx semaphore delete TX SEMAPHORE semaphore ptr Description This service deletes the specified counting semaphore All threads suspended waiting for a semaphore instance are resumed and given a TX DELETED return status t is the application s responsibility to prevent use of a deleted I semaphore Input Parameters semaphore ptr Pointer to a previously created semaphore Return Values TX SUCCESS 0x00 Successful counting semaphore deletion TX_SEMAPHORE_ERROR Ox0C Invalid counting semaphore pointer TX_CALLER_ERROR 0x13 Invalid caller of this service Allowed From Threads Preemption Possible Yes rin d User Guide Counting Semaphores 167 Example TX SEMAPHORE my semaphore UINT status Delete counting semaphore Assume that the counting semaphore has already been created status tx semaphore delete amp my semaphore If status equals TX SUCCESS the counting semaphore is deleted See Also tx_semaphore_ create tx_semaphore_ get tx_semaphore_info_get tx semaphore prioritize tx semaphore put Express Logic Inc 168 Description of ThreadX Services tx semaphore get Get instance from counting semaphore Prototype UINT tx semaphore get TX SEMAPHORE semaphore ptr ULONG wait option Description This service retrieves an instance a single count from the specified counting semaphore As a result the specified semaphore s count is decreased
100. e For example TX INITIALIZE IN PROGRESS is specific to the initialization component and is defined in the file tx ini h ThreadX C structure and typedef names are similar to the component specific constant names described previously System wide typedefs have the form TX C NAME Just like the constant names the C stands for the capitalized entire component name For example the queue control structure typedef is called TX QUEUE To limit the number of ThreadX include files an application must deal with the component specific typedefs that would normally be defined in the component specification files are contained in tx api h ERIS User Guide ThreadX Member Names ThreadX Global Data ThreadX Local Data ThreadX Function Names Coding Conventions 263 For greater readability primitive data types like UINT ULONG VOID etc do not require the leading TX modifier All primitive ThreadX data types are defined in the file tx port h ThreadX structure member names are all lower case and take on the form tx c name where c is the entire component name which is also the same as the parent structure or typedef name For example the thread identification field in the TX THREAD structure is named tx thread id Each ThreadX component has a small amount of global C data elements All global data elements are lower case and have the form tx c name Like other ThreadX names the c represents the entire com
101. e Error Checking Event Flag Create Event Flag Cleanup Event Flag Delete Event Flag Get Event Flag Initialize Event Flag Information Get Event Flag Set Event Flag Create Error Checking Event Flag Delete Error Checking Event Flag Get Error Checking Event Flag Information Get Error Checking Event Flag Set Error Checking Initialize High Level Initialize Kernel Entry Point Express Logic Inc 318 ThreadX Source Files TX SC C Semaphore Create TX SCLE C Semaphore Cleanup TX SD C Semaphore Delete TX SG C Semaphore Get TX SI C Semaphore Initialize TX SIG C Semaphore Information Get TX SP C Semaphore Put TX SPRI C Semaphore Prioritize TXE SC C Semaphore Create Error Checking TXE SD C Semaphore Delete Error Checking TXE SG C Semaphore Get Error Checking TXE SIGC Semaphore Information Get Error Checking TXE SP C Semaphore Put Error Checking TXE SPRI C Semaphore Prioritize Error Checking TX MC C Mutex Create TX MCLE C Mutex Cleanup TX MD C Mutex Delete TX MG C Mutex Get TX MI C Mutex Initialize TX MIG C Mutex Information Get TX MP C Mutex Put TX MPC C Mutex Priority Change TX MPRI C Mutex Prioritize TXE MC C Mutex Create Error Checking TXE MD C Mutex Delete Error Checking TXE MG C Mutex Get Error Checking TXE MIG C Mutex Information Get Error Checking TXE MP C Mutex Put Error Checking MPRI C Mutex Prioritize Error Checking ERIS User Guide ThreadX C Source Files 319 TX QC C TX QCLE C TX QD C
102. e no limits on the number of threads that can be created by an application The characteristics of each thread are contained in its control block This structure is defined in the tx api h file A thread s control block can be located anywhere in memory but it is most common to make the control block a global structure by defining it outside the scope of any function Locating the control block in other areas requires a bit more care just like all dynamically allocated memory If a control block is allocated within a C function the memory associated with it is part of the calling thread s stack In general using local storage for control blocks should be avoided because once the function returns then all of its local variable stack space is released regardless of whether another thread is using it for a control block In most cases the application is oblivious to the contents of the thread s control block However there are some situations especially in debug where looking at certain members is quite useful The Express Logic Inc 58 Functional Components of ThreadX following are a few of the more useful control block members tx run count This member contains a counter of how many times the thread has been scheduled An increasing counter indicates the thread is being scheduled and executed tx state This member contains the state of the associated thread The following list represents the possible threa
103. e on context switch overhead assume a three thread environment with threads named thread 1 thread 2 and thread 3 Assume further that all of the threads are in a state of suspension waiting for a message When thread 1 receives a message it immediately forwards it to thread 2 Thread 2 then forwards the message to thread 3 Thread 3 just discards the message After each thread processes its message they go back and wait for another The processing required to execute these three threads varies greatly depending on their priorities If all of the threads have the same priority a single context switch occurs between their execution The context switch occurs when each thread suspends on an empty message queue However if thread 2 is higher priority than thread 1 and thread 3 is higher priority than thread 2 the number of context switches doubles This is because another context switch occurs inside of the tx queue send service when it detects that a higher priority thread is now ready The ThreadX preemption threshold mechanism can avoid these extra context switches and still allow the previously mentioned priority selections This is a really important feature because it allows several thread priorities during scheduling while at the same time eliminating some of the unwanted context switching between them during thread execution ERIS User Guide Debugging Pitfalls Message Queues 65 Debugging multi threaded application
104. e receive TX QUEUE queue ptr VOID destination ptr ULONG wait option tx queue send TX QUEUE queue ptr VOID source ptr ULONG wait option Express Logic Inc 300 Semaphore unr UINT UINT UINT UINT UINT Mutex UINT Services UINT UINT UINT UINT UINT ThreadX API Services tx semaphore create SEMAPHORE semaphore ptr CHAR name_ptr ULONG initial_count tx semaphore delete semaphore ptr tx semaphore get TX SEMAPHORE semaphore ptr ULONG wait option tx semaphore info get TX SEMAPHORE semaphore ptr CHAR name ULONG current value TX THREAD first suspended ULONG suspended count X SEMAPHORE next semaphore tx semaphore prioritize TX SEMAPHORE semaphore ptr tx semaphore put TX SEMAPHORE semaphore ptr tx mutex create TX MUTEX mutex ptr CHAR name ptr UINT inherit tx mutex delete TX MUTEX mutex ptr tx mutex get TX MUTEX mutex ptr ULONG wait option tx mutex info get TX MUTEX mutex ptr CHAR name ULONG count TX THREAD owner TX THREAD first suspended ULONG suspended count TX MUTEX next mutex tx mutex prioritize TX MUTEX mutex ptr tx mutex put TX MUTEX mutex ptr ELITS gt User Guide ThreadX API Services 301 Thread UINT tx thread create TX THREAD thread ptr CHAR name ptr Control VOID entry function ULONG ULONG entry input VOID stack start ULONG stack size Se
105. e status and statistics associated with the driver operation Information managed by this function area typically includes the following Current device status Input bytes Output bytes I O error counts This functional area is optional It is only required if the driver and or the physical hardware device need to be shut down After terminated the driver must not be called again until it is re initialized Simple Driver Example Simple Driver Initialization An example is the best way to describe an I O driver In this example the driver assumes a simple serial hardware device with a configuration register an input register and an output register This simple driver example illustrates the initialization input output and interrupt functional areas The tx sdriver initialize function of the simple driver creates two counting semaphores that are ERIS User Guide Simple Driver Example 227 used to manage the driver s input and output operation The input semaphore is set by the input ISR when a character is received by the serial hardware device Because of this the input semaphore is created with an initial count of zero Conversely the output semaphore indicates the availability of the serial hardware transmit register It is created with a value of one to indicate the transmit register is initially available The initialization function is also responsible for installing the low level interrupt vector handlers fo
106. eal time 23 77 82 224 real time software 23 real time systems 44 56 re created 54 recursive algorithms 61 redundant polling 26 reentrancy 62 reentrant 62 reentrant function 62 register 263 register variables 256 relative time 85 remove error checking code from final image 39 reset 49 50 reset file 36 reset 68 36 reset arm 35 reset mip 36 reset ppc 36 reset sh 36 responsive processing 56 re started 54 re starting 54 ROM 46 47 ROM requirements 30 round robin scheduling 54 run time 56 62 80 82 run time behavior 27 run time environment 61 run time image 22 Express Logic Inc 332 S scalability 256 scalable 22 256 259 scheduling 50 scheduling loop 59 scheduling threads 44 semaphore component 283 semaphore control block 70 74 semaphore services 300 semaphores 50 52 72 259 semi independent program segment 50 service call time outs 30 service prototypes 31 simple 230 simple driver initialization 226 228 simple driver input 228 simple driver output 229 230 simple driver shortcomings 230 simplicity 256 slow memory 48 small example system 35 software components 258 software maintenance 26 source code ThreadX 30 source code indentation 264 stack 45 59 stack area is too small 61 stack memory area 61 stack overflow 37 stack pointer 58 stack size 65 240 stack sizes 37 stack space 57 stacks 48 50 standard package 31 starvation 56 63 starve 62
107. ecific Include processor specific Queue Component Include Thread Control Component Include Timer Component Include Semaphore Component Include ThreadX C Source Files TX BA C TX BPC C TX BPCLE C TX BPD C TX BPI C TX BPIG C TX BPP C TX BR C TXE BA C TXE BPC C TXE BPD C TXE BPIG C TXE BPP C TXE BR C Block Memory Allocate Block Pool Create Block Pool Cleanup Block Pool Delete Block Pool Initialize Block Pool Information Get Block Pool Prioritize Block Memory Release Block Allocate Error Checking Block Pool Create Error Checking Block Pool Delete Error Checking Block Pool Information Get Error Checking Block Pool Prioritize Error Checking Block Release Error Checking ERIS User Guide ThreadX C Source Files 317 TX BYTA C TX BYTC C TX BYTCL C TX BYTD C TX BYTI C TX BYTIG C TX BYTPP C TX BYTR C TX BYTS C TXE BYTA C TXE BYTC C TXE BYTD C TXE BYTG C TXE BYTP C TXE BYTR C TX EFC C TX EFCLE C TX EFD C TX EFG C TX EFI C TX EFIG C TX EFS C TXE EFC C TXE EFD C TXE EFG C TXE EFIG C TXE EFS C TX IHL C TX IKE C Byte Memory Allocate Byte Pool Create Byte Pool Cleanup Byte Pool Delete Byte Pool Initialize Byte Pool Information Get Byte Pool Prioritize Byte Memory Release Byte Pool Search Byte Allocate Error Checking Byte Pool Create Error Checking Byte Pool Delete Error Checking Byte Pool Information Get Error Checking Byte Pool Prioritize Error Checking Byte Pool Releas
108. ed directly by other ThreadX components What makes up a ThreadX component Each ThreadX component is comprised of a specification include file an initialization function and one or more action functions As mentioned previously each ThreadX function is defined in its own file If it were not for the design goal of scalable code size component files would likely contain more than one function In general Express Logic recommends a more than one function per file approach to application development There are nine functional ThreadX components Each component has the same basic construction and its processing and data structures are easily distinguished from those of other components The following lists ThreadX software components Initialize Thread Timer Queue Semaphore Mutex Event Flags Block Memory Byte Memory Each ThreadX software component has a specification file The specification file is a standard C include file that contains all component constants data types external and internal component function prototypes and even the component s global data definitions Express Logic Inc 260 Component Initialization Component Body Functions Internal Composition of ThreadX The specification file is included in all component files and in files of other components that need to access the individual component s functions Each component has an initialization function which is responsible f
109. ed on real time applications Because of this it is virtually impossible to provide a common set of drivers that will meet the requirements of every application For these reasons the information in this chapter is designed to help users customize off the shelf ThreadX I O drivers and write their own specific drivers Driver Functions ThreadX I O drivers are composed of eight basic functional areas as follows Driver Initialization Driver Control Driver Access Driver Input Driver Output Driver Interrupts Driver Status Driver Termination With the exception of initialization each driver functional area is optional Furthermore the exact processing in each area is specific to the I O driver ERIS User Guide Driver Functions 225 Driver Initialization This functional area is responsible for initialization of the actual hardware device and the internal data structures of the driver Calling other driver services is not allowed until initialization is complete The driver s initialization function component is typically called from the tx application define function or from an initialization thread Driver Control After the driver is initialized and ready for operation this functional area is responsible for run time control Typically run time control consists of making changes to the underlying hardware device Examples include changing the baud rate of a serial device or seeking a new sector on a disk D
110. efined in this file The global data for the block memory component is defined in this file and consists of the following data elements ERIS User Guide TX BA C TX BPC C TX BPCLE C TX BPD C TX BPI C TX BPIG C Block Memory Component 291 tx block pool created ptr This TX BLOCK POOL pointer is the head pointer of the created block memory pool list The list is a doubly linked circular list of all created block pool control blocks tx block pool created count This ULONG represents the number of created application block memory pools This file contains tx block allocate which is responsible for processing block allocation requests This file contains tx block pool create which is responsible for processing block memory pool create requests This file contains tx block pool cleanup which is responsible for processing block memory suspension time outs block memory suspended thread termination and thread wait abort requests This file contains tx block pool delete which is responsible for processing block memory pool delete requests This file contains tx block pool initialize which is responsible for initialization of the block memory pool component This file contains tx block pool info get which is responsible for block pool information retrieval Express Logic Inc 292 TX BPP C TX BR C TXE BA C TXE BPC C TXE BPD C TXE BPIG C TXE BPP C
111. elete tx timer info get Express Logic Inc 212 Description of ThreadX Services tx timer change Prototype Change an application timer UINT tx timer change TX TIMER timer ptr ULONG initial ticks ULONG reschedule ticks Description This service changes the expiration characteristics of the specified application timer The timer must be deactivated prior to calling this service A call to the tx timer activate service is required after this service in I order to start the timer again Input Parameters timer ptr Pointer to a timer control block initial ticks Specifies the initial number of ticks for timer expiration Legal values range from 1 through OxFFFFFFFF reschedule ticks Specifies the number of ticks for all timer expirations after the first A zero for this parameter makes the timer a one shot timer Otherwise for periodic timers legal values range from 1 through OxFFFFFFFF Return Values TX SUCCESS 0x00 TX TIMER ERROR 0x15 TX TICK ERROR 0x16 TX CALLER ERROR 0x13 ERIS User Guide Successful application timer change Invalid application timer pointer Invalid value a zero supplied for initial ticks Invalid caller of this service Application Timers 213 Allowed From Threads timers and ISRs Preemption Possible No Example TX TIMER my timer UINT status Change a previously created and now deactivated timer to expire every 50 timer ticks including
112. elopment tool initialization 48 49 development tools 46 distribution disk contents 31 distribution file 245 distribution files 31 dividing the application 27 DMA 231 downloading target 30 driver access 224 225 driver control 224 225 driver example 226 driver function 224 driver initialization 224 225 driver input 224 225 driver interrupts 224 226 driver output 224 225 driver status 224 226 driver termination 224 226 dynamic memory 46 48 dynamic memory usage 48 E ease of use 27 embedded application 23 embedded applications 23 24 definition 23 multitasking 24 embraces avoided 71 enables automatic MULTI error checking for ThreadX API calls 39 entry function 298 entry point 51 event flag component 288 event flag group control block 76 event flag services 299 event flags 50 52 75 259 event logging 39 sub option 40 event logging for associated ThreadX C source file 39 event logging for the ThreadX demonstration 32 event notification 68 69 72 example of suspended threads 71 excessive timers 85 executing 52 executing state 52 execution initialization 45 interrupt service routines ISR 44 execution context 59 execution overview 44 external events 64 F fast memory 48 faster time to market 27 FIFO order 67 70 73 79 81 first available RAM 50 first fit 80 first in first out FIFO 54 fixed size 78 fixed size memory 77 fixed sized messages 66 fragmentation 77 80 fragmented 81
113. emory area of a very ERIS User Guide Thread Suspension Queue Control Block TX QUEUE Message Queues 67 important queue in high speed RAM in order to improve performance Application threads can suspend while attempting to send or receive a message from a queue Typically thread suspension involves waiting for a message from an empty queue However it is also possible for a thread to suspend trying to send a message to a full queue After the condition for suspension is resolved the service requested is completed and the waiting thread is resumed If multiple threads are suspended on the same queue they are resumed in the order they were suspended FIFO However priority resumption is also possible if the application calls tx queue prioritize prior to the queue service that lifts thread suspension The queue prioritize service places the highest priority thread at the front of the suspension list while leaving all other suspended threads in the same FIFO order Time outs are also available for all queue suspensions Basically a time out specifies the maximum number of timer ticks the thread will stay suspended If a time out occurs the thread is resumed and the service returns with the appropriate error code The characteristics of each message queue are found in its control block It contains interesting information such as the number of messages in the queue This structure is defined in the tx api h file
114. emption Possible No Example TX MUTEX my mutex CHAR name ULONG count TX THREAD owner TX THREAD first suspended ULONG suspended count TX MUTEX next mutex UINT status Retrieve information about a the previously created mutex my mutex Status tx mutex info get amp my mutex amp name amp count amp owner amp first suspended amp suspended count amp next mutex If status equals TX SUCCESS the information requested is valid See Also tx mutex create tx mutex delete tx mutex get tx mutex prioritize tx mutex put Express Logic Inc 142 Description of ThreadX Services tx mutex prioritize Prioritize mutex suspension list Prototype UINT tx mutex prioritize TX MUTEX mutex ptr Description This service places the highest priority thread suspended for ownership of the mutex at the front of the suspension list All other threads remain in the same FIFO order they were suspended in Input Parameters mutex ptr Pointer to the previously created mutex Return Values TX SUCCESS 0x00 Successful mutex prioritize TX MUTEX ERROR 0x1C Invalid mutex pointer Allowed From Initialization threads timers and ISRs Preemption Possible No ELITSE gt User Guide Mutex 143 Example TX MUTEX my mutex UINT status Ensure that the highest priority thread will receive ownership of the mutex when it becomes available status tx mutex prioritize amp my
115. emption of higher priority threads Input Parameters thread ptr Pointer to application thread Return Values TX SUCCESS 0x00 Successful thread terminate TX THREAD ERROR 0x0E Invalid application thread pointer TX CALLER ERROR 0x13 Invalid caller of this service Allowed From Threads and timers Preemption Possible Yes ELITS I User Guide Thread Control 201 Example TX THREAD my thread UINT status Terminate the thread represented by my thread Status tx thread terminate amp my thread If status equals TX SUCCESS the thread is terminated and cannot execute again until it is deleted and re created See Also tx thread create tx thread delete tx thread identify tx thread info get tx thread preemption change tx thread priority change tx thread relinquish tx thread resume tx thread sleep tx thread suspend tx thread time slice change tx thread wait abort Express Logic Inc 202 Description of ThreadX Services tx thread time slice change Changes time slice of application thread Prototype UINT tx thread time slice change TX THREAD thread ptr ULONG new time slice ULONG old time slice Description This service changes the time slice of the specified application thread Selecting a time slice for a thread insures that it won t execute more than the specified number of timer ticks before other threads of the same or higher priorities have a chance to e
116. end indefinitely until there is room in the queue Selecting a numeric value 1 OxFFFFFFFE specifies the maximum number of timer ticks to stay suspended while waiting for room in the queue Message Queues 163 Return Values TX SUCCESS 0x00 Successful sending of message TX DELETED 0x01 Message queue was deleted while thread was suspended TX QUEUE FULL 0x0B Service was unable to send message because the queue was full TX WAIT ABORTED 0x1A Suspension was aborted by another thread timer or ISR TX QUEUE ERROR 0x09 Invalid message queue pointer TX PTR ERROR 0x03 Invalid source pointer for message TX WAIT ERROR 0x04 A wait option other than TX NO WAIT was specified on a call from a non thread Allowed From Initialization threads timers and ISRs Preemption Possible Yes Example TX QUEUE my queue UINT status ULONG my_message 4 Send a message to my queue Return immediately regardless of success This wait option is used for calls from initialization timers and ISRs status tx queue send amp my queue my message TX NO WAIT If status equals TX SUCCESS the message is in the queue See Also tx queue create tx queue delete tx queue flush tx queue front send tx queue info get tx queue prioritize tx queue receive Express Logic Inc 164 Description of ThreadX Services tx semaphore create Create a counting semaphore Prototype UINT tx semap
117. ension was aborted by another thread timer or ISR TX CALLER ERROR 0x13 Service called from a non thread Allowed From Threads Preemption Possible Yes ELITS gt User Guide Thread Control 197 Example UINT status Make the calling thread sleep for 100 timer ticks status tx thread sleep 100 If status equals TX SUCCESS the currently running application thread slept for the specified number of timer ticks See Also tx thread create tx thread delete tx thread identify tx thread info get tx thread preemption change tx thread priority change tx thread relinquish tx thread resume tx thread suspend tx thread terminate tx thread time slice change tx thread wait abort Express Logic Inc 198 Description of ThreadX Services tx thread suspend Suspend an application thread Prototype UINT tx thread suspend TX THREAD thread ptr Description This service suspends the specified application thread A thread may call this service to suspend itself suspension is held internally until the prior suspension is lifted When that happens this unconditional suspension of the specified thread is performed Further unconditional suspension requests have no effect If the specified thread is already suspended for another reason this Once suspended the thread must be resumed by tx thread resume in order to execute again Input Parameters thread ptr Pointer to an appl
118. ent Flags 127 Express Logic Inc 128 Description of ThreadX Services tx event flags info get Retrieve information about event flags group X EVENT FLAGS GROUP group ptr R name ULONG current flags EVENT FLAGS GROUP next group Prototype UINT tx event flags info get 1 CHA TX THREAD first suspended ULONG suspended count TX Description This service retrieves information about the specified event flags group Input Parameters group ptr name current flags first suspended suspended count next group Return Values TX SUCCESS TX GROUP ERROR TX PTR ERROR ERIS User Guide Pointer to an event flags group control block Pointer to destination for the pointer to the event flag group s name Pointer to destination for the current set flags in the event flag group Pointer to destination for the pointer to the thread that is first on the suspension list of this event flag group Pointer to destination for the number of threads currently suspended on this event flag group Pointer to destination for the pointer of the next created event flag group 0x00 Successful event group information retrieval 0x06 Invalid event group pointer 0x03 Invalid pointer NULL for any destination pointer Event Flags 129 Allowed From Initialization threads timers and ISRs Preemption Possible No Example TX EVENT FLAGS GROUP my event group CHAR name ULONG cur
119. equals TX SUCCESS the mutex ownership count has been decremented and if zero released See Also tx mutex create tx mutex delete tx mutex get tx mutex info get tx mutex prioritize Express Logic Inc 146 Description of ThreadX Services tx queue create Create a message queue Prototype UINT tx queue create TX QUEUE queue ptr CHAR name ptr UINT message size VOID queue start ULONG queue size Description This service creates a message queue that is typically used for inter thread communication The total number of messages is calculated from the specified message size and the total number of bytes in the queue evenly divisible by the specified message size the remaining bytes in the If the total number of bytes specified in the queue s memory area is not I memory area are not used Input Parameters queue ptr Pointer to a message queue control block name ptr Pointer to the name of the message queue message size Specifies the size of each message in the queue Message sizes range from 1 32 bit word to 16 32 bit words Valid message size options are defined as follows TX 1 ULONG 0x01 TX 2 ULONG 0x02 TX 4 ULONG 0x04 TX 8 ULONG 0x08 TX 16 ULONG 0x10 queue start Starting address of the message queue queue size Total number of bytes available for the message queue ERIS User Guide Message Queues 147 Return Values TX SUCCESS 0x00 Successful message queue creation T
120. equests to read the system clock tx timer system clock This file contains tx time set which is responsible for processing requests to set the tx timer system clock to a specified value ERIS User Guide TX TIMI C TX TIMIG C TX TIMIN S ASM TX TTE C TXE TAA C TXE TDA C TXE TIMD C TXE TIMI C Timer Component 279 This file contains tx timer initialize which is responsible for initialization of the timer component This file contains tx timer info get which is responsible for retrieving information about a timer This file contains tx timer interrupt which is responsible for processing actual timer interrupts The interrupt processing is typically optimized to reduce overhead if neither a timer nor a time slice has expired This file contains tx timer thread entry which is responsible for the processing of the internal timer thread This file contains txe timer activate api which is responsible for checking application timer activate requests for errors This file contains txe timer deactivate api which is responsible for checking application timer deactivate requests for errors This file contains txe timer delete which is responsible for checking application timer delete requests for errors This file contains txe timer info get which is responsible for checking application timer information get requests Express Logic Inc 280 Internal Composition of ThreadX TXE
121. er of counting semaphores in an application Application threads can suspend while attempting to perform a get operation on a semaphore with a current count of 0 Once a put operation is performed the suspended thread s get operation is performed and the thread is resumed If multiple threads are suspended on the Express Logic Inc 70 Semaphore Control Block TX SEMAPHORE Deadly Embrace Functional Components of ThreadX same counting semaphore they are resumed in the same order they were suspended FIFO However priority resumption is also possible if the application calls tx semaphore prioritize prior to the semaphore put call that lifts thread suspension The semaphore prioritize service places the highest priority thread at the front of the suspension list while leaving all other suspended threads in the same FIFO order The characteristics of each counting semaphore are found in its control block It contains interesting information such as the current semaphore count This structure is defined in the tx api h file Semaphore control blocks can be located anywhere in memory but it is most common to make the control block a global structure by defining it outside the scope of any function One of the most interesting and dangerous pitfalls associated with semaphores used for mutual exclusion is the deadly embrace A deadly embrace or deadlock is a condition where two or more threads are suspended i
122. essages received 035 ULONG thread 3 counter 036 ULONG thread_4 counter 037 ULONG thread_5 counter 038 ULONG thread 6 counter 039 ULONG thread 7 counter 040 041 Define thread prototypes 042 043 void thread 0 entry ULONG thread input 044 void thread 1 entry ULONG thread input 045 void thread 2 entry ULONG thread input 046 void thread 3 and 4 entry ULONG thread input 047 void thread 5 entry ULONG thread input 048 void thread 6 and 7 entry ULONG thread input 049 050 051 Define main entry point 052 053 int main 054 055 056 Enter the ThreadX kernel 057 tx kernel enter 058 059 060 Define what the initial system looks like 061 void tx application define void first unused memory 062 063 064 CHAR pointer 065 066 Create a byte memory pool from which to allocate the thread stacks 067 tx byte pool create amp byte pool 0 byte pool 0 first_unused_memory 068 DEMO BYTE POOL SIZE 069 070 Put system definition stuff in here e g thread creates and other assorted 071 create information TETTES User Guide 072 073 074 075 076 077 078 079 080 081 082 083 084 085 086 087 088 089 090 091 092 093 094 095 096 097 098 099 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 13 132 133 134 135 136 137 138 13
123. ex create 134 tx mutex delete 136 tx mutex get 72 138 tx mutex info get 140 tx mutex prioritize 73 142 tx mutex put 72 144 TX MUTEX SUSP 0x0D 58 tx next buffer 235 tx next packet 234 TX NO EVENT INFO 39 TX OR CONSUME 75 tx port h 19 31 33 257 263 TX QC C 280 TX QCLE C 281 TX QD C 281 TX QF C 281 TX QFS C 281 TX QI C 281 TX QIG C 281 TX QP C 281 TX QR C 281 TX QS C 282 TX QUE H 280 TX QUEUE 262 tx queue create 146 tx queue delete 148 tx queue flush 150 tx queue front send 87 152 tx queue info get 87 154 tx queue prioritize 67 87 156 tx queue receive 65 87 158 tx queue send 64 65 87 162 TX QUEUE SUSP 0x05 58 TX READY 0x00 58 tx run count 58 TX SC C 283 TX SCLE C 284 286 TX SD C 284 286 tx sdriver initialize 226 tx sdriver input 228 tx sdriver output 230 TX SEM H 283 285 TX SEMAPHORE 70 tx semaphore create 164 tx semaphore delete 166 tx semaphore get 68 87 168 tx semaphore info get 87 170 tx semaphore prioritize 70 87 172 tx semaphore put 68 87 174 TX SEMAPHORE SUSP 0x06 58 TX SG C 284 286 TX SI C 284 286 TX SIG C 284 TX SLEEP 0x04 58 TX SP C 284 287 TX SPRI C 284 tx state 58 TX SUSPENDED 0x03 58 TX TA C 277 TX TAA C 278 TX TC C 269 tx tc c 39 261 264 TX TCR 269 TX TCS 270 TX TD C 278 TX TDA C 278 TX TDEL 270 TX TDEL C 270 TX TERMINATED 0x02 58 TX THR H 267 tx thr h 263 TX THREAD 48 263 tx thread create 52
124. f Express Logic Inc 40 Installation and Use of ThreadX needed this option should be added to the txe bld file TX ENABLE EVENT FILTERS This conditional compilation flag is another sub option for event logging If this flag is defined run time filtering logic is added to the event logging code If needed this option should be added to the txe bld file Additional conditional compilation options are described in the readme txt supplied on the distribution disk ThreadX Version ID The current version of ThreadX is available to both the user and the application software during run time The programmer can find the ThreadX version in the readme txt file This file also contains a version history of the corresponding port Application software can obtain the ThreadX version by examining the global string tx version id ELITSE a gt User Guide Functional Components of ThreadX This chapter contains a description of the high performance ThreadX kernel from a functional perspective Each functional component is presented in an easy to understand manner m Execution Overview 44 Initialization 44 Thread Execution 44 Interrupt Service Routines ISR 44 Initialization 45 Application Timers 46 m Memory Usage 46 Static Memory Usage 46 Dynamic Memory Usage 48 em Initialization 48 System Reset 49 Development Tool Initialization 49 main 49 tx kernel enter 49 Application Definition Function 50 Interrupts
125. f these applications must also perform certain activities at pre determined intervals of time ThreadX application timers provide applications with the ability to execute application C functions at specific intervals of time It is also possible for an application timer to expire only once This type of timer is called a one shot timer while repeating interval timers are called periodic timers Each application timer is a public resource ThreadX places no constraints on how application timers are used In ThreadX time intervals are measured by periodic timer interrupts Each timer interrupt is called a timer tick The actual time between timer ticks is specified by the application but 10ms is the norm for most implementations The periodic timer setup is typically found in the tx ill assembly file It is worth mentioning that the underlying hardware must have the ability to generate periodic interrupts in order for application timers to function In some cases the processor has a built in periodic interrupt capability If the processor doesn t have this ability the user s board must have a peripheral device that can generate periodic interrupts ThreadX can still function even without a periodic interrupt source However all timer related processing is then disabled This includes time slicing suspension time outs and timer services Express Logic Inc 84 Timer Accuracy Timer Execution Creating Application
126. found ThreadX transfers control to it Once the thread is finished or another higher priority thread becomes ready execution transfers back to the thread scheduling loop in order to find the next highest priority ready thread This process of continually executing and scheduling threads is the most common type of program execution in ThreadX applications Interrupts are the cornerstone of real time systems Without interrupts it would be extremely difficult to respond to changes in the external world in a timely manner What happens when an interrupt occurs Upon detection of an interrupt the processor saves key information about the current program execution ERIS User Guide Execution Overview 45 Execution Overview Hardware Reset Initialization Thread Execution Interrupt Service Routines Application Timers FIGURE 2 Types of Program Execution usually on the stack then transfers control to a predefined program area This predefined program area is commonly called an Interrupt Service Routine What type of program execution was interrupted In most cases interrupts occur during thread execution or in the thread scheduling loop However Express Logic Inc 46 Application Timers Functional Components of ThreadX interrupts may also occur inside of an executing ISR or an Application Timer Application timers are very similar to ISRs except the actual hardware
127. g in its scheduling loop for a thread to become ready Each thread must have its own stack for saving the context of its last execution and compiler use Most C compilers use the stack for making function calls and for temporarily allocating local variables Figure 6 shows a typical thread s stack Where is a thread stack located This is really up to the application The stack area is specified during thread creation and can be located anywhere in the target s address space This is a very important feature because it allows applications to improve performance of important threads by placing their stack in high speed RAM How big should a stack be This is one of the most frequently asked questions about threads A thread s stack area must be large enough to accommodate worst case function call nesting local variable allocation and saving its last execution context The minimum stack size TX MINIMUM STACK is defined by ThreadX A stack of this size supports Express Logic Inc 60 physical addresses 0x0000F200 Y 0x0000FC00 Functional Components of ThreadX Stack Memory Area example Typical run time stack growth tx stack ptr Thread s last execution context Local variables and C function nesting FIGURE 6 Typical Thread Stack saving a thread s context and minimum amount of function calls and local variable allocation For most threads the minimum stack size is simply
128. gic Inc 268 Internal Composition of ThreadX used by the scheduling loop to determine which thread to execute next tx thread created ptr This TX THREAD pointer is the head pointer of the created thread list The list is a doubly linked circular list of all created thread control blocks tx thread created count This ULONG contains the number of currently created threads in the system tx thread system state This ULONG contains the current system state It is set during initialization and during interrupt processing to disable internal thread switching inside of the ThreadX services tx thread preempted map This ULONG represents each of the 32 thread priority levels in ThreadX with a single bit A set bit indicates that a thread of the corresponding priority level was preempted when it had preemption threshold in force tx thread priority map This ULONG represents each of the 32 thread priority levels in ThreadX with a single bit It is used to find the next lower priority ready thread when a higher priority thread suspends tx thread highest priority This UINT contains the priority of the highest priority thread ready for execution tx thread lowest bit This array of UCHARS contains a table lookup for quickly finding the lowest bit set in a byte This is used in examination of the ERIS User Guide TX TC C TX TCR S ASM Thread Component 269 tx thread priority map to find the
129. he fact ThreadX insulates applications from details of the underlying processors makes ThreadX applications highly portable As a result the application s migration path is guaranteed and the original development investment is protected Express Logic Inc 28 Introduction to ThreadX TID User Guide Installation and Use of ThreadX This chapter contains a description of various issues related to installation setup and usage of the high performance ThreadX kernel with the Green Hills MULTI development environment m Host Considerations 30 em Target Considerations 30 Product Distribution 31 m ThreadX Installation 33 em Using ThreadX 33 m Small Example System 35 m Troubleshooting 37 m Configuration Options 38 m ThreadX Version ID 40 ERIS gt User Guide 30 Installation and Use of ThreadX Host Considerations Embedded development is usually performed on Windows or Unix host computers After the application is compiled and linked it is downloaded to the target hardware for execution Target download is typically done through the debug interface which is typically JTAG However downloading can also be done over serial parallel and Ethernet interfaces Review the Green Hills Target Connection User s Guide for available debug connection options The source code for ThreadX is delivered in ASCII format and requires approximately 1 MByte of space on the host computer s hard d
130. he same FIFO order they were suspended in Input Parameters semaphore ptr Pointer to a previously created semaphore Return Values TX SUCCESS 0x00 Successful semaphore prioritize TX SEMAPHORE ERROR Ox0C Invalid counting semaphore pointer Allowed From Initialization threads timers and ISRs Preemption Possible No rin d User Guide Counting Semaphores 173 Example TX SEMAPHORE my semaphore UINT status Ensure that the highest priority thread will receive the next instance of this semaphore Status tx semaphore prioritize amp my semaphore If status equals TX SUCCESS the highest priority suspended thread is at the front of the list The next tx semaphore put call made to this queue will wake up this thread See Also tx semaphore create tx semaphore delete tx semaphore get tx semaphore info get tx semaphore put Express Logic Inc 174 Description of ThreadX Services tx semaphore put Place an instance in counting semaphore Prototype UINT tx semaphore put SEMAPHORE semaphore ptr Description This service puts an instance into the specified counting semaphore which in reality increments the counting semaphore by one f this service is called when the semaphore is all ones OxFFFFFFFF I the new put operation will cause the semaphore to be reset to zero Input Parameters semaphore ptr Pointer to the previously created counting semaphore control block
131. he same time Events are set by ix event flags set and are retrieved by tx event flags get Setting event flags is done with a logical AND OR operation between the current event flags and the new event flags The type of logical operation either an AND or OR is specified in the tx event flags set call There are similar logical options for retrieval of event flags A get request can specify that all specified event flags are required a logical AND Alternatively a get request can specify that any of the specified event flags will satisfy the request a logical OR The type of logical operation associated with event flag retrieval is specified in the ix event flags get call Event flags that satisfy a get request are consumed i e set to zero if TX OR CLEAR or TX AND CLEAR are specified by the request Express Logic Inc 76 Creating Event Flag Groups Thread Suspension i Event Flag Group Control Block TX EVENT FLAGS GROUP Functional Components of ThreadX Each event flag group is a public resource ThreadX places no constraints on how event flag groups are used Event flag groups are created either during initialization or during run time by application threads At time of their creation all event flags in the group are set to zero There are no limits on the number of event flag groups in an application Application threads can suspend while attempting to get any logical combination of even
132. he specified number of bytes from the specified byte memory pool The performance of this service is a function of the block size and the amount of fragmentation in the pool Hence this service should not be used during time critical threads of execution Input Parameters pool ptr Pointer to a previously created memory pool memory ptr Pointer to a destination memory pointer On successful allocation the address of the allocated memory area is placed where this parameter points to memory size Number of bytes requested wait option Defines how the service behaves if there is not enough memory available The wait options are defined as follows TX NO WAIT 0x00000000 TX WAIT FOREVER OxFFFFFFFF timeout value 0x00000001 through OxFFFFFFFE Selecting TX NO WAIT results in an immediate return from this service regardless of whether or not it was successful This is the only valid option if the service is called from initialization Selecting TX WAIT FOREVER causes the calling thread to suspend indefinitely until enough memory is available ERIS User Guide Memory Bytes 107 Selecting a numeric value 1 OxFFFFFFFE specifies the maximum number of timer ticks to stay suspended while waiting for the memory Return Values TX SUCCESS 0x00 TX DELETED 0x01 TX NO MEMORY 0x10 TX WAIT ABORTED 0x1A TX POOL ERROR 0x02 TX PTR ERROR 0x03 TX WAIT ERROR 0x04 TX CALLER ERROR 0x13 Allowed From Initia
133. he system clock legal values range from 0 through OxFFFFFFFF Return Values None Allowed From Threads timers and ISRs Preemption Possible No TID User Guide Time Ticks 209 Example Set the internal system time to 0x1234 tx time set 0x1234 Current time now contains 0x1234 until the next timer interrupt See Also tx time get Express Logic Inc 210 Description of ThreadX Services tx timer activate Activate an application timer Prototype UINT tx timer activate TX TIMER timer ptr Description This service activates the specified application timer The expiration routines of timers that expire at the same time are executed in the order they were activated Input Parameters timer ptr Pointer to a previously created application timer Return Values TX SUCCESS 0x00 Successful application timer activation TX TIMER ERROR 0x15 Invalid application timer pointer TX ACTIVATE ERROR 0x17 Timer was already active Allowed From Initialization threads timers and ISRs Preemption Possible No TID User Guide Application Timers 211 Example TX TIMER my timer UINT status Activate an application timer Assume that the application timer has already been created status tx timer activate amp my timer If status equals TX SUCCESS the application timer is now active See Also tx timer change tx timer create tx timer deactivate tx timer d
134. her application may require optimized driver ISRs because of high frequency device interrupts Buffering Data buffering in real time embedded applications requires considerable planning Some of the design is dictated by the underlying hardware device If the device provides basic byte I O a simple circular buffer is probably in order However if the device provides block DMA or packet I O a buffer management scheme is probably warranted Circular Byte Circular byte buffers are typically used in drivers that Buffers manage a simple serial hardware device like a UART Two circular buffers are most often used in such situations one for input and one for output Each circular byte buffer is comprised of a byte memory area typically an array of UCHARS a read pointer and a write pointer A buffer is considered empty when the read pointer and the write pointers reference the same memory location in the buffer Driver initialization sets both the read and write buffer pointers to the beginning address of the buffer Circular Buffer The input buffer is used to hold characters that arrive Input before the application is ready for them When an input character is received usually in an interrupt service routine the new character is retrieved from the hardware device and placed into the input buffer at the location pointed to by the write pointer The write pointer is then advanced to the next position in Express Logic Inc
135. hest priority thread will receive the next message placed on this queue Status tx queue prioritize amp my queue If status equals TX SUCCESS the highest priority suspended thread is at the front of the list The next tx queue send or tx queue front send call made to this queue will wake up this thread See Also tx queue create tx queue delete tx queue flush tx queue front send tx queue info get tx queue receive tx queue send Express Logic Inc 158 Description of ThreadX Services tx queue receive Get a message from message queue Prototype UINT tx queue receive TX QUEUE queue ptr VOID destination ptr ULONG wait option Description This service retrieves a message from the specified message queue The retrieved message is copied from the queue into the memory area specified by the destination pointer That message is then removed from the queue message i e the message destination pointed to by destination ptr must be at least as large as the message size for this queue Otherwise if the destination is not large enough memory corruption occurs in the following memory area The specified destination memory area must be large enough to hold the Input Parameters queue ptr Pointer to a previously created message queue destination ptr Location of where to copy the message wait option Defines how the service behaves if the message queue is empty The wait options are defined as fol
136. hore create TX SEMAPHORE semaphore ptr CHAR name ptr ULONG initial count Description This service creates a counting semaphore for inter thread synchronization The initial semaphore count is specified as an input parameter Input Parameters semaphore ptr Pointer to a semaphore control block name ptr Pointer to the name of the semaphore initial count Specifies the initial count for this semaphore Legal values range from 0x00000000 through OxFFFFFFFF Return Values TX SUCCESS 0x00 Successful semaphore creation TX SEMAPHORE ERROR Ox0C Invalid semaphore pointer Either the pointer is NULL or the semaphore is already created TX CALLER ERROR 0x13 Invalid caller of this service Allowed From Initialization and threads Preemption Possible No ERIS User Guide Counting Semaphores 165 Example TX SEMAPHORE my semaphore UINT status Create a counting semaphore whose initial value is 1 This is typically the technique used to make a binary semaphore Binary semaphores are used to provide protection over a common resource Status tx semaphore create amp my semaphore my semaphore name 1 If status equals TX SUCCESS my semaphore is ready for use See Also tx semaphore delete tx semaphore get tx semaphore info get tx semaphore prioritize tx semaphore put Express Logic Inc 166 Description of ThreadX Services tx semaphore delete Delete a counting semaphor
137. ht amount of system overhead Since time slicing is only useful in cases where multiple threads share the same priority threads having a unique priority should not be assigned a time slice Specifies whether the thread starts immediately or is placed in a suspended state Legal options are TX AUTO START 0x01 and TX DONT START 0x00 If TX DONT START is specified the application must later call tx thread resume in order for the thread to run Express Logic Inc 178 Description of ThreadX Services Return Values TX SUCCESS TX THREAD ERROR TX PTR ERROR TX SIZE ERROR TX PRIORITY ERROR TX THRESH ERROR TX START ERROR TX CALLER ERROR Allowed From Initialization and threads Preemption Possible Yes rin d User Guide 0x00 0x0E 0x03 0x05 0x0F 0x18 0x10 0x13 Successful thread creation Invalid thread control pointer Either the pointer is NULL or the thread is already created Invalid starting address of the entry point or the stack area is invalid usually NULL Size of stack area is invalid Threads must have at least TX_MINIMUM_STACK bytes to execute Invalid thread priority which is a value outside the range of 0 31 Invalid preemption threshold specified This value must be a valid priority less than or equal to the initial priority of the thread Invalid auto start selection Invalid caller of this service Thread Control 179 Example
138. i t the f t of the specified queue See Also tx queue create tx queue delete tx queue flush tx queue info get tx queue prioritize tx queue receive tx queue send Express Logic Inc 154 Description of ThreadX Services tx queue info get Retrieve information about a queue Prototype UINT tx queue info get TX QUEUE queue ptr CHAR name ULONG enqueued ULONG available storage TX THREAD first suspended ULONG suspended count TX QUEUE next queue Description This service retrieves information about the specified message queue Input Parameters queue ptr Pointer to a previously created message queue name Pointer to destination for the pointer to the queue s name enqueued Pointer to destination for the number of messages currently in the queue available storage Pointer to destination for the number of messages the queue currently has space for first suspended Pointer to destination for the pointer to the thread that is first on the suspension list of this queue suspended count Pointer to destination for the number of threads currently suspended on this queue next queue Pointer to destination for the pointer of the next created queue Return Values TX SUCCESS 0x00 Successful queue information get TX QUEUE ERROR 0x09 Invalid message queue pointer TX PTR ERROR 0x03 Invalid pointer NULL for any destination pointer Allowed From Initialization threads timers and ISRs
139. ible for checking queue information retrieve requests for errors This file contains txe queue prioritize which is responsible for checking queue prioritize requests for errors This file contains txe queue receive which is responsible for checking queue receive requests for errors ERIS User Guide Semaphore Component 283 TXE QS C This file contains txe queue send which is responsible for checking queue send requests for errors Semaphore Component This component is responsible for all semaphore management activities including semaphore creation deletion semaphore gets and semaphore puts TX SEM H This is the specification file for the ThreadX Semaphore Component All component constants external interfaces and data structures are defined in this file The global data for the semaphore component is defined in this file and consists of the following data elements tx semaphore created ptr This TX SEMAPHORE pointer is the head pointer of the created semaphore list The list is a doubly linked circular list of all created semaphore control blocks tx semaphore created count This ULONG represents the number of created application semaphores TX SC C This file contains tx semaphore create which is responsible for processing semaphore create requests Express Logic Inc 284 TX SCLE C TX SD C TX SG C TX SI C TX SIG C TX SP C TX SPRI C TXE SC C Internal Composition
140. ibuted only with the premium package tx a This is the binary version of the ThreadX C library It is distributed with the standard package All files and batch file commands are in lower case This naming convention makes it easier to convert the commands to Unix development platforms ES User Guide ThreadX Installation 33 ThreadX Installation 6 0000 Installation of ThreadX is straightforward The steps below apply to virtually all ThreadX installations However please refer to the supplied Express Start Guide and readme txt file for information about specific ThreadX distribution Backup the ThreadX distribution disk and store it in a safe location On the host hard drive make a unique ThreadX directory The ThreadX distribution will reside in this directory Copy all files from the ThreadX distribution CD ROM into the directory created in step 2 If the standard package was ordered installation of ThreadX is now complete If the premium package was purchased invoke Green Hills MULTI and open the ThreadX build file tx bld Next select the BUILD button and observe the ThreadX library being built When this completes the resulting ThreadX library file tx a can be used by the application Application software needs access to the ThreadX library file tx a and the C include files tx api h and tx port h This is accomplished either by setting the appropriate path for the development tools or by copyi
141. ication thread Return Values TX SUCCESS 0x00 Successful thread suspend TX THREAD ERROR OxOE Invalid application thread pointer TX SUSPEND ERROR 0x14 Specified thread is in a terminated or completed state TX CALLER ERROR 0x13 Invalid caller of this service Allowed From Threads and timers Preemption Possible Yes el gt User Guide Thread Control 199 Example TX THREAD my thread UINT status Suspend the thread represented by my thread status tx thread suspend amp my thread If status equals TX SUCCESS the application thread is unconditionally suspended See Also tx thread create tx thread delete tx thread identify tx thread info get tx thread preemption change tx thread priority change tx thread relinquish tx thread resume tx thread sleep tx thread terminate tx thread time slice change tx thread wait abort Express Logic Inc 200 Description of ThreadX Services tx thread terminate Terminates an application thread Prototype UINT tx thread terminate TX THREAD thread ptr Description This service terminates the specified application thread regardless of whether the thread is suspended or not A thread may call this service to terminate itself terminated the thread must be deleted and re created in order for it I to execute again Note that time slicing is disabled when using preemption threshold to I prevent pre
142. id if error checking is disabled by TX DISABLE ERROR CHECKING option TX DISABLE STACK CHECKING By default the thread create ERIS User Guide Configuration Options 39 function fills the thread s stack with a OxEF data pattern which is used by the MULTI debugger to calculate stack usage This can be disabled by compiling the ThreadX source file tx tc c with this conditional compilation flag defined TX ENABLE EVENT LOGGING Defining this conditional compilation flag enables event logging for the associated ThreadX C source file If this option is used anywhere the tx ihl c file must be compiled with this flag defined since this is where the event log is initialized The txe bld and demo el bld files found in the distribution utilize this define to enable event logging throughout the ThreadX library and demonstration system TX ENABLE MULTI ERROR CHECKING This conditional complication flag enables automatic MULTI error checking for the ThreadX API calls Basically all non bold ThreadX API return values can be detected by MULTI automatically if the ThreadX application is built with this conditional defined After the application is fully debugged it can be re built with TX DISABLE ERROR CHECKING to remove unnecessary error checking code from the final image TX NO EVENT INFO This conditional compilation flag is a sub option for event logging If this flag is defined only basic information is saved in the log I
143. ied by the USER or that the operation of the ThreadX products will operate uninterrupted or error free or that any defects that may exist in the ThreadX products will be corrected after the warranty period Express Logic Inc makes no warranties of any kind either expressed or implied including but not limited to the implied warranties of merchantability and fitness for a particular purpose with respect to the ThreadX products No oral or written information or advice given by Express Logic Inc its dealers distributors agents or employees shall create any other warranty or in any way increase the scope of this warranty and licensee may not rely on any such information or advice Part Number 000 4001 Revision G4 0c Express Logic Inc Contents Figures 15 About This Guide 17 m Organization 17 m Guide Conventions 18 m ThreadX Data Types 19 m Customer Support Center 20 Where to Send Comments 20 1 Introduction to ThreadX 21 m ThreadX Unique Features 22 picokernel Architecture 22 ANSI C Source Code 22 Not A Black Box 22 A Potential Standard 23 m Embedded Applications 23 Real time Software 23 Multitasking 24 Tasks vs Threads 24 m ThreadX Benefits 25 Improved Responsiveness 25 Software Maintenance 26 Increased Throughput 26 Processor Isolation 26 Dividing the Application 27 Ease of Use 27 Improve TETEN User Guide 4 ThreadX Time to market 27 Protecting the Software Investment 27
144. ile leaving all other suspended threads in the same FIFO order The characteristics of each memory block pool are found in its control block It contains information such as the number of memory blocks left and their size This structure is defined in the tx api h file Pool control blocks can also be located anywhere in memory but it is most common to make the control block a global structure by defining it outside the scope of any function It is very important to ensure that the user of an allocated memory block does not write outside its boundaries If this happens corruption occurs in an adjacent usually subsequent memory area The results are unpredictable and quite often fatal Memory Byte Pools ThreadX memory byte pools are similar to a standard C heap Unlike the standard C heap it is possible to have multiple memory byte pools In addition threads can suspend on a pool until the requested memory is available Express Logic Inc 80 Creating Memory Byte Pools Pool Capacity Functional Components of ThreadX Allocations from memory byte pools are similar to traditional malloc calls which include the amount of memory desired in bytes Memory is allocated from the pool in a first fit manner i e the first free memory block that satisfies the request is used Excess memory from this block is converted into a new block and placed back in the free memory list This process is called fragmentation A
145. ill always stay within one of each other VOID my first thread ULONG thread input Endless loop of relinquish while 1 Increment the run counter run counter 1 Relinquish control to other thread tx thread relinquish VOID my second thread ULONG thread input Endless loop of relinquish while 1 Increment the run counter run counter 2 Relinquish control to other thread tx thread relinquish See Also tx thread create tx thread delete tx thread identify tx thread info get tx thread preemption change tx thread priority change tx thread resume tx thread sleep tx thread suspend tx thread terminate tx thread time slice change tx thread wait abort Express Logic Inc 194 Description of ThreadX Services tx thread resume Resume suspended application thread Prototype UINT tx thread resume TX THREAD thread ptr Description This service resumes or prepares for execution a thread that was previously suspended by a tx thread suspend call In addition this service resumes threads that were created without an automatic start Input Parameters thread ptr Pointer to a suspended application thread Return Values TX SUCCESS 0x00 Successful thread resume TX SUSPEND LIFTED 0x19 Previously set delayed suspension was lifted TX THREAD ERROR 0x0E Invalid application thread pointer TX RESUME ERROR 0x
146. imer info get Express Logic Inc 216 Description of ThreadX Services tx timer deactivate Deactivate an application timer Prototype UINT tx timer deactivate TX TIMER timer ptr Description This service deactivates the specified application timer If the timer is already deactivated this service has no effect Input Parameters timer ptr Pointer to a previously created application timer Return Values TX SUCCESS 0x00 Successful application timer deactivation TX TIMER ERROR 0x15 Invalid application timer pointer Allowed From Initialization threads timers and ISRs Preemption Possible No ELITS gt User Guide Application Timers 217 Example TX TIMER my timer UINT status Deactivate an application timer Assume that the application timer has already been created status tx timer deactivate amp my timer If status equals TX SUCCESS the application timer is now deactivated See Also tx timer activate tx timer change tx timer create tx timer delete tx timer info get Express Logic Inc 218 Description of ThreadX Services tx timer delete Delete an application timer Prototype UINT tx timer delete TX TIMER timer ptr Description This service deletes the specified application timer It is the application s responsibility to prevent use of a deleted timer Input Parameters timer ptr Pointer to a previously created application timer Retur
147. imer itself a TX FALSE value is returned Otherwise if the timer is active a TX TRUE value is returned Pointer to destination for the number of timer ticks left before the timer expires Pointer to destination for the number of timer ticks that will be used to automatically reschedule this timer If the value is zero then the timer is a one shot and won t be rescheduled Pointer to destination for the pointer of the next created application timer 0x00 Successful timer information retrieval 0x15 Invalid application timer pointer 0x03 Invalid pointer NULL for any destination pointer Application Timers 221 Allowed From Initialization threads timers and ISRs Preemption Possible No Example TX TIMER my timer HAR name INT active LONG remaining ticks LONG reschedule ticks X TIMER next timer UINT status C W U U T Retrieve information about a the previously created application timer my timer status tx timer info get amp my timer amp name amp active amp remaining ticks amp reschedule ticks amp next timer If status equals TX SUCCESS the information requested is valid See Also tx timer activate tx timer change tx timer create tx timer deactivate tx timer delete tx timer info get Express Logic Inc 222 Description of ThreadX Services TID User Guide IIO Drivers for ThreadX This chapter contains a description of I
148. ing point for initial run time memory allocations of thread stacks queues and memory pools After initialization is complete only an executing thread can create and delete system resources including other threads Therefore at least one thread must be created during initialization Interrupts are left disabled during the entire initialization process If the application somehow enables interrupts unpredictable behavior may occur Figure 4 on page 51 shows the entire initialization process from system reset through application specific initialization Thread Execution Scheduling and executing application threads is the most important activity of ThreadX What exactly is a thread A thread is typically defined as semi ERIS User Guide Thread Execution 51 System Reset Initialization Process entry point development tool initialization main tx kernel enter tx application define mem ptr Enter thread scheduling loop denotes functions that are development tool specific FIGURE 4 Initialization Process independent program segment with a dedicated purpose The combined processing of all threads makes an application Express Logic Inc 52 Thread Execution States Functional Components of ThreadX How are threads created Threads are created dynamically by calling tx thread create during initialization or during thread execution Threads are created in either a ready or suspended s
149. ion threads are allocated processing time Prior to real time kernels like ThreadX most embedded applications allocated processing time with a simple control loop usually from within the C main function This approach is still used in very small or simple applications However in large or complex applications it is not practical because the response time to any event is a function of the worst case processing time of one pass through the control loop Making matters worse the timing characteristics of the application change whenever modifications are made to the control loop This makes the application inherently unstable and very difficult to maintain and improve on ThreadX provides fast and deterministic response times to important external events ThreadX accomplishes this through its preemptive priority based scheduling algorithm which allows a higher priority thread to preempt an executing lower priority thread As a result the worst case response time approaches the time required to perform a context switch This is not only deterministic but it is also extremely fast Express Logic Inc 26 Software Maintenance Increased Throughput Processor Isolation Introduction to ThreadX The ThreadX kernel enables application developers to concentrate on specific requirements of their application threads without having to worry about changing the timing of other areas of the application This feature also m
150. is allocation of processing between competing tasks is the primary purpose of ThreadX Another distinction about tasks must be made The term task is used in a variety of ways It sometimes means a separately loadable program In other instances it might refer to an internal program segment In contemporary operating system discussion there are two terms that more or less replace the use of task namely process and thread process is a completely independent program that has its own address space while a thread is a semi independent program segment that executes within a process Threads share the same process address space The overhead associated with thread management is minimal Most embedded applications cannot afford the overhead both memory and performance associated with a full blown process oriented operating system In addition smaller microprocessors don t have the hardware architecture to support a true process oriented operating system For these reasons ThreadX implements a thread model which is both extremely efficient and practical for most real time embedded applications el gt User Guide ThreadX Benefits 25 To avoid confusion ThreadX does not use the term task Instead the more descriptive and contemporary name thread is used ThreadX Benefits Improved Responsiveness Using ThreadX provides many benefits to embedded applications Of course the primary benefit rests in how embedded applicat
151. is preempted it will resume before other ready threads of equal priority for the remainder of its time slice Using time slicing results in a slight amount of system overhead Since time slicing is only useful in cases where multiple threads share the same priority threads having a unique priority should not be assigned a time slice Preemption is the process of temporarily interrupting an executing thread in favor of a higher priority thread This process is invisible to the executing thread When the higher priority thread is finished control is transferred back to the exact place where the preemption took place Express Logic Inc 56 Preemption Threshold i Functional Components of ThreadX This is a very important feature in real time systems because it facilitates fast response to important application events Although a very important feature preemption can also be a source of a variety of problems including starvation excessive overhead and priority inversion In order to ease some of the inherent problems of preemption ThreadX provides a unique and advanced feature called preemption threshold What is a preemption threshold A preemption threshold allows a thread to specify a priority ceiling for disabling preemption Threads that have higher priorities than the ceiling are still allowed to preempt while those less than the ceiling are not allowed to preempt For example suppose a thread of
152. isk Please review the supplied readme txt file for additional host system considerations and options Target Considerations ThreadX requires between 2 KBytes and 20 KBytes of Read Only Memory ROM on the target Another 1 to 2 KBytes of the targets Random Access Memory RAM are required for the ThreadX system stack and other global data structures For proper operation of timer related functions such as service call time outs time slicing and application timers the target hardware must provide a periodic interrupt source If the processor has this capability built in it is utilized by ThreadX Otherwise if the target processor does not have the ability to generate a periodic interrupt the user s hardware must provide it Setup and configuration of the timer interrupt is located in the tx ill assembly file in the ThreadX distribution ERIS User Guide Product Distribution 31 If no periodic timer interrupt source is available I ThreadX is still functional However none of the timer related services are functional Please review the supplied readme txt file for any additional host system considerations and or options Product Distribution ThreadX is shipped on a single CD ROM compatible disk Two types of ThreadX packages are available standard and premium The standard package includes minimal source code while the premium package contains complete ThreadX Source code The exact contents of the distri
153. ity to manage the memory area Input Parameters queue ptr Pointer to a previously created message queue Return Values TX SUCCESS 0x00 Successful message queue deletion TX QUEUE ERROR 0x09 Invalid message queue pointer TX CALLER ERROR 0x13 Invalid caller of this service Allowed From Threads Preemption Possible Yes ELITSE gt User Guide Message Queues 149 Example TX QUEUE my queue UINT status Delete entire message queue Assume that the queue has already been created with a call to tx queue create Status tx queue delete amp my queue If status equals TX SUCCESS the message queue is deleted See Also tx queue create tx queue flush tx queue front send tx queue info get tx queue prioritize tx queue receive tx queue send Express Logic Inc 150 Description of ThreadX Services tx queue flush Empty messages in a message queue Prototype UINT tx queue flush TX QUEUE queue ptr Description This service deletes all messages stored in the specified message queue If the queue is full messages of all suspended threads are discarded Each suspended thread is then resumed with a return status that indicates the message send was successful If the queue is empty this service does nothing Input Parameters queue ptr Pointer to a previously created message queue Return Values TX SUCCESS 0x00 Successful message queue flush TX QUEUE ERROR 0x09 Inv
154. ive Time Interrupts Relative Time 85 By default application timers execute from within a hidden system thread that runs at priority zero which is higher than any application thread Because of this processing inside application timers should be kept to a minimum It is also important to avoid whenever possible timers that expire every timer tick Such a situation might induce excessive overhead in the application As mentioned previously application timers are executed from a hidden system thread It is therefore very important not to select suspension on any ThreadX service calls made from within the application timer s expiration function In addition to the application timers mentioned previously ThreadX provides a single continuously incrementing 32 bit tick counter The tick counter or time is increased by one on each timer interrupt The application can read or set this 32 bit counter through calls to tx time get and tx time set respectively The use of this tick counter is determined completely by the application It is not used internally by ThreadX Fast response to asynchronous events is the principal function of real time embedded applications How does the application know such an event is present Typically this is accomplished through hardware interrupts Express Logic Inc 86 Interrupt Control ThreadX Managed Interrupts Functional Components of ThreadX An interrupt is an as
155. ize kernel enter which coordinates the initialization and start up processing of ThreadX Note that the tx kernel enter function used by the application is mapped to this routine ERIS User Guide TX ILL S ASM Thread Component 267 This file contains tx initialize low level which handles all assembly language initialization processing This file is processor and development tool specific Thread Component TX THR H This component is responsible for all thread management activities including thread creation scheduling and interrupt management The thread component is the most processor compiler specific of all ThreadX components hence it has the most assembly language files This is the specification file for the ThreadX Thread Component All component constants external interfaces and data structures are defined in this file The global data for the thread component is defined in this file and consists of the following data elements tx thread system stack ptr This VOID pointer contains the address of the system stack pointer The system stack is used inside of the ThreadX scheduling loop and inside of interrupt processing tx thread current ptr This TX THREAD pointer contains the address of the currently running thread s control block If this pointer is NULL the system is idle tx thread execute ptr This TX THREAD pointer contains the address of the next thread to execute and is Express Lo
156. k ptr Description This service releases a previously allocated block back to its associated memory pool If there are one or more threads suspended waiting for memory block from this pool the first thread suspended is given this memory block and resumed The application must prevent using a memory block area after it has been released back to the pool Input Parameters block ptr Pointer to the previously allocated memory block Return Values TX SUCCESS 0x00 Successful memory block release TX PTR ERROR 0x03 Invalid pointer to memory block Allowed From Initialization threads timers and ISRs Preemption Possible Yes TID User Guide Memory Blocks 105 Example TX BLOCK POOL my pool unsigned char memory ptr UINT status Release a memory block back to my pool Assume that the pool has been created and the memory block has been allocated Status tx block release VOID memory ptr If status equals TX SUCCESS the block of memory pointed to by memory ptr has been returned to the pool See Also tx block allocate tx block pool create tx block pool delete tx block pool info get tx block pool prioritize Express Logic Inc 106 Description of ThreadX Services tx byte allocate Allocate bytes of memory Prototype UINT tx byte allocate TX BYTE POOL pool ptr VOID memory ptr ULONG memory size ULONG wait option Description This service allocates t
157. l for such developers Because of its versatility high performance picokernel architecture and great portability ThreadX has the potential to become an industry standard for embedded applications Embedded Applications Real time Software What is an embedded application Embedded applications are applications that execute on microprocessors buried inside of products like cellular phones communication equipment automobile engines laser printers medical devices etc Another distinction of embedded applications is that their software and hardware have a dedicated purpose When time constraints are imposed on the application software it is given the real time label Basically software that must perform its processing within an exact period of time is called real time software Embedded applications are almost always real time because of their inherent interaction with the external world Express Logic Inc 24 Multitasking Tasks vs Threads Introduction to ThreadX As mentioned embedded applications have a dedicated purpose In order to fulfill this purpose the software must perform a variety of duties or tasks A task is a semi independent portion of the application that carries out a specific duty It is also the case that some tasks or duties are more important than others One of the major difficulties in an embedded application is the allocation of the processor between the various application tasks Th
158. l is specified during creation Like other memory areas in ThreadX it can be located anywhere in the target s address space This is an important feature because of the considerable flexibility it gives the application For example if the target hardware has a high speed memory area and a low speed memory area the user can manage memory allocation for both areas by creating a pool in each of them Application threads can suspend while waiting for memory bytes from a pool When sufficient contiguous memory becomes available the suspended threads are given their requested memory and resumed If multiple threads are suspended on the same memory byte pool they are given memory resumed in the order they were suspended FIFO However priority resumption is also possible if the application calls tx byte pool prioritize prior to the byte release call that lifts thread suspension The byte pool prioritize service places the highest priority thread at the front of the suspension list while leaving all other suspended threads in the same FIFO order Express Logic Inc 82 Memory Byte Pool Control Block TX BYTE POOL Un deterministic Behavior il Overwriting Memory Blocks Functional Components of ThreadX The characteristics of each memory byte pool are found in its control block It contains useful information such as the number of available bytes in the pool This structure is defined in the tx_api h file P
159. l of the initial system resources including threads queues semaphores mutexes event flags and memory pools The demonstration system s tx application define line numbers 60 164 creates the demonstration objects in the following order byte pool 0 thread 0 thread 1 thread 2 thread 3 thread 4 thread 5 thread 6 el gt User Guide Initial Execution Application Define 241 thread 7 queue 0 semaphore 0 event flags 0 mutex 0 block pool 0 The demonstration system does not create any other additional ThreadX objects However an actual application may create system objects during run time inside of executing threads All threads are created with the TX AUTO START option This makes them initially ready for execution After tx application define completes control is transferred to the thread scheduler and from there to each individual thread The order in which the threads execute is determined by their priority and the order that they were created In the demonstration system thread 0 executes first because it has the highest priority it was created with a priority of 1 After thread 0 suspends thread 5 is executed followed by the execution of thread 3 thread 4 thread 6 thread 7 thread 1 and finally thread 2 Notice that even though thread 3 and thread 4 have the same priority both created with a priority of 8 thread 3 executes first This is because thread 3 was created and became ready before th
160. leted mutex Input Parameters mutex ptr Pointer to a previously created mutex Return Values TX SUCCESS 0x00 Successful mutex deletion TX MUTEX ERROR 0x1C Invalid mutex pointer TX CALLER ERROR 0x13 Invalid caller of this service Allowed From Threads Preemption Possible Yes ELITSE gt User Guide Mutex 137 Example TX MUTEX my mutex UINT status Delete a mutex Assume that the mutex has already been created Status tx mutex delete amp my mutex If status equals TX SUCCESS the mutex is deleted See Also tx mutex create tx mutex get tx mutex info get tx mutex prioritize tx mutex put Express Logic Inc 138 Description of ThreadX Services tx mutex get Obtain ownership of a mutex Prototype UINT tx mutex get TX MUTEX mutex ptr ULONG wait option Description This service attempts to obtain exclusive ownership of the specified mutex If the calling thread already owns the mutex an internal counter is incremented and a successful status is returned If the mutex is owned by another thread and this thread is higher priority and priority inheritance was specified at mutex create the lower priority thread s priority will be temporarily raised to that of the calling thread priority inheritance should never be modified by an external thread during Note that the priority of the lower priority thread owning a mutex with I mutex ownership Input Parameters
161. lf Suspend Terminate Service Self Terminate Return From Thread Entry Function FIGURE 5 Thread State Transition A thread in a completed state indicates the thread completed its processing and returned from its entry function Remember that the entry function is specified during thread creation A thread in a completed state cannot execute again A thread is in a terminated state because another thread or itself called the tx thread terminate Express Logic Inc 54 i Thread Priorities Thread Scheduling Round Robin Scheduling Functional Components of ThreadX service A thread in a terminated state cannot execute again If re starting a completed or terminated thread is desired the application must first delete the thread It can then be re created and re started As mentioned before a thread is defined as a semi independent program segment with a dedicated purpose However all threads are not created equal The dedicated purpose of some threads is much more important than others This heterogeneous type of thread importance is a hallmark of embedded real time applications How does ThreadX determine a thread s importance When a thread is created it is assigned a numerical value representing its importance or priority Valid numerical priorities range between 0 and 31 where a value of 0 indicates the highest thread priority and a value of 31 represents the lowest thread priority Threa
162. lization and threads Preemption Possible Yes Successful memory allocation Memory pool was deleted while thread was suspended Service was unable to allocate the memory Suspension was aborted by another thread timer or ISR Invalid memory pool pointer Invalid pointer to destination pointer A wait option other than TX NO WAIT was specified on a call from a non thread Invalid caller of this service Express Logic Inc 108 Description of ThreadX Services Example TX BYTE POOL my pool unsigned char memory ptr UINT status Allocate a 112 byte memory area from my pool Assume that the pool has already been created with a call to tx byte pool create status tx byte allocate amp my pool VOID amp memory ptr 112 TX NO WAIT If status equals TX SUCCESS memory ptr contains the address of the allocated memory area See Also tx byte pool create tx byte pool delete tx byte pool info get tx byte pool prioritize tx byte release ELITSE gt User Guide Memory Bytes 109 Express Logic Inc 110 Description of ThreadX Services tx byte pool create Create a memory pool of bytes Prototype UINT tx byte pool create TX BYTE POOL pool ptr CHAR name ptr VOID pool start ULONG pool size Description This service creates a memory pool in the area specified Initially the pool consists of basically one very large free block However the pool is broke
163. llowed From Initialization threads timers and ISRs Preemption Possible Yes Example TX SEMAPHORE my semaphore UINT status Get a semaphore instance from the semaphore my semaphore If the semaphore count is zero suspend until an instance becomes available Note that this suspension is only possible from application threads Status tx semaphore get amp my semaphore TX WAIT FOREVER status equals i e rea as obtaine If stat ls TX_SUCCESS the th dh btained an instance of the semaphore See Also tx_semaphore_create tx_semahore_delete tx_semaphore_info_get tx semaphore prioritize tx semaphore put Express Logic Inc 170 Description of ThreadX Services tx semaphore info get Retrieve information about a semaphore Prototype UINT tx semaphore info get TX SEMAPHORE semaphore ptr CHAR name ULONG current value TX THREAD first suspended ULONG suspended count TX SEMAPHORE next semaphore Description This service retrieves information about the specified semaphore Input Parameters semaphore ptr name current value first suspended suspended count next semaphore Return Values Pointer to semaphore control block Pointer to destination for the pointer to the semaphore s name Pointer to destination for the current semaphore s count Pointer to destination for the pointer to the thread that is first on the suspension list of this semaphore P
164. lows TX NO WAIT 0x00000000 TX WAIT FOREVER OxFFFFFFFF timeout value 0x00000001 through OxFFFFFFFE Selecting TX_NO_WAIT results in an immediate return from this service regardless of whether or not it was successful This is the only valid option if the service is called from a non thread e g Initialization timer or ISR Selecting TX_WAIT_FOREVER causes the calling thread to suspend indefinitely until a message is available el gt User Guide Message Queues 159 Selecting a numeric value 1 OxFFFFFFFE specifies the maximum number of timer ticks to stay suspended while waiting for a message Return Values TX SUCCESS 0x00 Successful retrieval of message TX DELETED 0x01 Message queue was deleted while thread was suspended TX QUEUE EMPTY 0xOA Service was unable to retrieve a message because the queue was empty TX WAIT ABORTED 0x1A Suspension was aborted by another thread timer or ISR TX QUEUE ERROR 0x09 Invalid message queue pointer TX PTR ERROR 0x03 Invalid destination pointer for message TX WAIT ERROR 0x04 Await option other than TX NO WAIT was specified on a call from a non thread Allowed From Initialization threads timers and ISRs Preemption Possible Yes Express Logic Inc 160 Description of ThreadX Services Example TX QUEUE my queue UINT status ULONG my message 4 Retrieve a message from my queue If the queue is empty suspend until a me
165. major pitfall associated with mutual exclusion is priority inversion This topic is discussed more fully in Thread Priority Pitfalls on page 62 The basic problem results from a situation where a lower priority thread has a semaphore that a higher priority thread needs This in itself is normal However threads with priorities in between them may cause the priority inversion to last a non deterministic amount of time Unlike semaphores discussed previously the ThreadX mutex object has optional priority inheritance The basic idea behind priority inheritance is that a lower priority thread has its priority raised temporarily to the priority of a high priority thread that wants the same mutex owned by the lower priority thread When the lower priority thread releases the mutex its original priority is then ERIS User Guide Event Flags i Event Flags 75 restored and the higher priority thread is given ownership of the mutex This feature eliminates un deterministic priority inversion by bounding the amount of inversion to the time the lower priority thread holds the mutex Of course the techniques discussed earlier in this chapter to handle un deterministic priority inversion are also valid with mutexes as well Event flags provide a powerful tool for thread synchronization Each event flag is represented by a single bit Event flags are arranged in groups of 32 Threads can operate on all 32 event flags in a group at t
166. mp pointer DEMO STACK SIZE TX NO WAIT tx thread create amp thread 4 thread 4 thread 3 and 4 entry 4 pointer DEMO STACK SIZE 8 8 TX NO TIME SLICE TX AUTO START Allocate the stack for thread 5 tx byte allocate amp byte pool 0 amp pointer DEMO STACK SIZE TX NO WAIT Create thread 5 This thread simply pends on an event flag which will be set by thread 0 tx thread create amp thread 5 thread 5 thread 5 entry 5 pointer DEMO STACK SIZE 4 4 TX NO TIME SLICE TX AUTO START Allocate the stack for thread 6 tx byte allocate amp byte pool 0 amp pointer DEMO STACK SIZE TX NO WAIT Create threads 6 and 7 These threads compete for a ThreadX mutex tx thread create amp thread 6 thread 6 thread 6 and 7 entry 6 pointer DEMO STACK SIZE 8 8 TX NO TIME SLICE TX AUTO START Allocate the stack for thread 7 tx byte allocate amp byte pool 0 amp pointer DEMO STACK SIZE TX NO WAIT tx thread create amp thread 7 thread 7 thread 6 and 7 entry 7 pointer DEMO STACK SIZE 8 8 TX NO TIME SLICE TX AUTO START Allocate the message queue tx byte allocate amp byte pool 0 amp pointer DEMO QUEUE SIZE sizeof ULONG TX NO WAIT Create the message queue shared by threads 1 and 2 247 tx queue create amp queue 0 queue 0 TX 1 ULONG pointer DEMO QUEUE SIZE sizeof ULONG Create the semaphore used by threads 3 and 4
167. mutex If status equals TX SUCCESS the highest priority suspended thread is at the front of the list The next tx mutex put call that releases ownership of the mutex will give ownership to this thread and wake it up See Also tx mutex create tx mutex delete tx mutex get tx mutex info get tx mutex put Express Logic Inc 144 Description of ThreadX Services tx mutex put Release ownership of mutex Prototype UINT tx mutex put TX MUTEX mutex ptr Description This service decrements the ownership count of the specified mutex If the ownership count is zero the mutex is made available the releasing thread will be restored to the priority it had when it originally obtained ownership of the mutex Any other priority changes made to the releasing thread during ownership of the mutex may be undone If priority inheritance was selected during mutex creation the priority of Input Parameters mutex ptr Pointer to the previously created mutex Return Values TX SUCCESS 0x00 Successful mutex release TX NOT OWNED Ox1E Mutex is not owned by caller TX MUTEX ERROR 0x1C Invalid pointer to mutex TX CALLER ERROR 0x13 Invalid caller of this service Allowed From Initialization and threads Preemption Possible Yes ELITSE gt User Guide Mutex 145 Example TX MUTEX my mutex UINT status Release ownership of my mutex status tx mutex put amp my mutex If status
168. n Values TX SUCCESS 0x00 Successful application timer deletion TX TIMER ERROR 0x15 Invalid application timer pointer TX CALLER ERROR 0x13 Invalid caller of this service Allowed From Threads Preemption Possible No ELITS gt User Guide Application Timers 219 Example TX TIMER my timer UINT status Delete application timer Assume that the application timer has already been created status tx timer delete amp my timer If status equals TX SUCCESS the application timer is deleted See Also tx timer activate tx timer change tx timer create tx timer deactivate tx timer info get Express Logic Inc 220 Description of ThreadX Services tx timer info get Retrieve information about an application timer Prototype UINT tx timer info get TIMER timer ptr CHAR name Description UINT active ULONG remaining ticks ULONG reschedule ticks TX TIMER next timer This service retrieves information about the specified application timer Input Parameters timer ptr name active remaining ticks reschedule ticks next timer Return Values TX SUCCESS TX TIMER ERROR TX PTR ERROR ERIS gt User Guide Pointer to a previously created application timer Pointer to destination for the pointer to the timer s name Pointer to destination for the timer active indication If the timer is inactive or this service is called from the t
169. n have limited usefulness Furthermore complicated coding standards or software design make source code products equally hard to use This chapter contains a clear and concise description of the internal composition of ThreadX m ThreadX Design Goals 256 Simplicity 256 Scalability 256 High Performance 256 ThreadX ANSI C Library 257 System Include Files 257 System Entry 258 Application Definition 258 m Software Components 258 ThreadX Components 259 Component Specification File 259 Component Initialization 260 Component Body Functions 260 Coding Conventions 260 ThreadX File Names 261 ThreadX Name Space 261 ThreadX Constants 262 ThreadX Struct and Typedef Names 262 ThreadX Member Names 263 ThreadX Global Data 263 ThreadX Local Data 263 ThreadX Function Names 263 Source Code Indentation 264 Comments 264 ERIS gt User Guide 252 Internal Composition of ThreadX lt Initialization Component 266 TX INI H 266 TX IHL C 266 TX IKE C 266 TX ILL S ASM 267 m Thread Component 267 TX THR H 267 TX TC C 269 TX TCR S ASM 269 TX TCS S ASM 270 TX TDEL C 270 TX TI C 270 TX TIC S ASM 270 TX TIDE C 270 TX TIG C 270 TX TPC S ASM 270 TX TPCH C 271 TX TPRCH C 271 TX TR C 271 TX TRA C 271 TX TREL C 271 TX TS S ASM 271 TX TSA C 271 TX TSB S ASM 272 TX TSE C 272 TX TSLE C 272 TX TSR S ASM 272 TX TSUS C 272 TX TT C 272 TX TTO C 273 TX TTS C 273 TX TTSC C 273 TX TWA C 273 TXE TC C 273 TXE TDEL C 27
170. n into smaller blocks as allocations are made Input Parameters pool ptr Pointer to a memory pool control block name ptr Pointer to the name of the memory pool pool start Starting address of the memory pool pool size Total number of bytes available for the memory pool Return Values TX SUCCESS 0x00 Successful memory pool creation TX POOL ERROR 0x02 Invalid memory pool pointer Either the pointer is NULL or the pool is already created TX PTR ERROR 0x03 Invalid starting address of the pool TX SIZE ERROR 0x05 Size of pool is invalid TX CALLER ERROR 0x13 Invalid caller of this service Allowed From Initialization and threads Preemption Possible No ERIS User Guide Memory Bytes 111 Example TX BYTE POOL my pool UINT status Create a memory pool whose total size is 2000 bytes Starting at address 0x500000 Status tx byte pool create amp my pool my pool name VOID 0x500000 2000 If status equals TX SUCCESS my pool is available for allocating memory See Also tx byte allocate tx byte pool delete tx byte pool info get tx byte pool prioritize tx byte release Express Logic Inc 112 Description of ThreadX Services tx byte pool delete Delete a memory pool of bytes Prototype UINT tx byte pool delete TX BYTE POOL pool ptr Description This service deletes the specified memory pool All threads suspended waiting for memory from this pool are
171. n thread 194 tx thread sleep Suspended current thread for specified time 196 tx thread suspend Suspend an application thread 198 tx thread terminate Terminates an application thread 200 tx thread time slice change Changes time slice of application thread 202 tx thread wait abort Abort suspension of specified thread 204 tx time get Retrieves the current time 206 tx time set Sets the current time 208 tx timer activate Activate an application timer 210 tx timer change Change an application timer 212 ERIS User Guide 93 tx timer create Create an application timer 214 tx timer deactivate Deactivate an application timer 216 tx timer delete Delete an application timer 218 tx timer info get Retrieve information about application timer 220 Express Logic Inc 94 Description of ThreadX Services tx block allocate Allocate a fixed size block of memory Prototype UINT tx block allocate TX BLOCK POOL pool ptr VOID block ptr ULONG wait option Description This service allocates a fixed size memory block from the specified memory pool The actual size of the memory block is determined during memory pool creation Input Parameters pool ptr Pointer to a previously created memory block pool block ptr Pointer to a destination block pointer On successful allocation the address of the allocated memory block is placed where this parameter points to wait option Defines how the service beh
172. n threshold of the specified thread The preemption threshold prevents preemption of the specified thread by threads equal to or less than the preemption threshold value Note that using preemption threshold disables time slicing for the I specified thread Input Parameters thread_ptr Pointer to a previously created application thread new_threshold New preemption threshold priority level 0 31 old_threshold Pointer to a location to return the previous preemption threshold Return Values TX_SUCCESS 0x00 Successful preemption threshold change TX_THREAD_ERROR 0x0E Invalid application thread pointer TX_THRESH_ERROR 0x18 Specified new preemption threshold is not a valid thread priority a value other than 0 31 or is greater than lower priority than the current thread priority TX_PTR_ERROR 0x03 Invalid pointer to previous preemption threshold storage location TX_CALLER_ERROR 0x13 Invalid caller of this service Allowed From Threads and timers ERIS User Guide Thread Control 189 Preemption Possible Yes Example TX THREAD my thread UINT my old threshold UINT status Disable all preemption of the specified thread The current preemption threshold is returned in my old threshold Assume that my thread has already been created status tx thread preemption change amp my thread 0 amp my old threshold If status equals TX SUCCESS the application thread is non preem
173. n time out associated with the get operation to recover from a deadly embrace Express Logic Inc 72 Priority Inversion Mutexes Functional Components of ThreadX Another pitfall associated with mutual exclusion semaphores is priority inversion This topic is discussed more fully in Thread Priority Pitfalls on page 62 The basic problem results from a situation where a lower priority thread has a semaphore that a higher priority thread needs This in itself is normal However threads with priorities in between them may cause the priority inversion to last a non deterministic amount of time This can be handled through careful selection of thread priorities using preemption thresholds and temporarily raising the priority of the thread that owns the resource to that of the high priority thread In addition to semaphores ThreadX also provides a mutex object A mutex is basically a binary semaphore which means that only one thread can own a mutex at a time In addition the same thread may perform a successful mutex get operation on an owned mutex multiple times 4 294 967 295 to be exact There are two operations on the mutex object namely tx mutex get and tx mutex put The get operation obtains a mutex not owned by another thread while the put operation releases a previously obtained mutex In order for a thread to release a mutex the number of put operations must equal the number of prior get operations
174. ndefinitely while attempting to get semaphores already owned by other threads This condition is best illustrated by a two thread two semaphore example Suppose the first thread owns the first semaphore and the second thread owns the second semaphore If the first thread attempts to get the second semaphore and at the same time the second thread attempts to get the first semaphore both threads enter a deadlock condition In addition if these threads stay suspended forever their associated resources are locked out forever as well Figure 8 on page 71 illustrates this example ERIS User Guide Counting Semaphores 71 Deadly Embrace example First Second Semaphore Semaphore owned by I second threa first thread attempt to attempt to get second get first semaphore semaphore First Thread Second Thread FIGURE 8 Example of Suspended Threads How are deadly embraces avoided Prevention in the application is the best method for real time systems This amounts to placing certain restrictions on how threads obtain semaphores Deadly embraces are avoided if threads can only have one semaphore at a time Alternatively threads can own multiple semaphores if they all gather them in the same order In the previous example if the first and second thread obtain the first and second semaphore in order the deadly embrace is prevented It is also possible to use the suspensio
175. ne of the most important aspects of multi threading It is sometimes very tempting to assign priorities based on a perceived notion of thread importance rather than determining what is exactly required during run time Misuse of thread priorities can starve other threads create priority inversion reduce processing bandwidth and make the application s run time behavior difficult to understand As mentioned before ThreadX provides a priority based preemptive scheduling algorithm Lower priority threads do not execute until there are no ERIS User Guide Thread Execution 63 higher priority threads ready for execution If a higher priority thread is always ready the lower priority threads never execute This condition is called thread starvation Most starvation problems are detected early in debug and can be solved by ensuring that higher priority threads don t execute continuously Alternatively logic can be added to the application that gradually raises the priority of starved threads until they get a chance to execute Another unpleasant pitfall associated with thread priorities is priority inversion Priority inversion takes place when a higher priority thread is suspended because a lower priority thread has a needed resource Of course in some instances it is necessary for two threads of different priority to share a common resource If these threads are the only ones active the priority inversion time is bounded by the
176. nent has one processor compiler specific function that is responsible for handling the physical timer interrupt This is the specification file for the ThreadX Timer Component All component constants external interfaces and data structures are defined in this file The global data for the timer component is defined in this file and consists of the following data elements tx timer system clock This ULONG contains a tick counter that increments on each timer interrupt tx timer time slice This ULONG contains the time slice of the current thread If this value is zero no time slice is active tx timer expired time slice This UINT is set if a time slice expiration is detected in the timer interrupt handling It is cleared once the time slice has been processed in the ISR tx timer list This array of active timer linked list head pointers is indexed by the timer s relative time displacement from the current time pointer Each timer expiration list is maintained in doubly linked circular fashion Express Logic Inc 276 Internal Composition of ThreadX tx timer list start This TX INTERNAL TIMER head pointer contains the address of the first timer list It is used to reset the tx timer current ptr to the beginning of tx timer list when a wrap condition is detected tx timer list end This TX INTERNAL TIMER head pointer contains the address of the end of the tx timer list array It is used t
177. next ready priority group tx thread priority list This array of TX THREAD list head pointers is directly indexed by thread priority If an entry is non NULL there is at least one thread at that priority ready for execution The threads in each priority list managed in a doubly linked circular list of thread control blocks The thread in the front of the list represents the next thread to execute for that priority tx thread preempt disable This UINT is an internal mechanism for ThreadX services to enter into internal critical section processing This reduces the amount of time interrupts need to be disabled inside of ThreadX services tx thread special string This array of CHAR contains initials of various people and institutions that have helped make ThreadX possible This file contains tx thread create which is responsible for creating application threads This file contains tx thread context restore which is responsible for processing at the end of managed ISRs This function is processor compiler specific and is typically written in assembly language Express Logic Inc 270 TX TCS S ASM TX TDEL C TX TI C TX TIC S ASM TX TIDE C TX TIG C TX TPC S ASM Internal Composition of ThreadX This file contains tx thread context save which is responsible for saving the interrupted context in the beginning of ISR processing This function is processor compiler specific and is
178. ng its Express Logic Inc 244 Demonstration System for ThreadX counter getting an event flag from thread 0 through event flags 0 and repeating the sequence Notice that thread 5 suspends whenever the event flag in event flags 0 is not available line 298 Threads 6 and 7 Observing the The function thread 6 and 7 entry marks the entry point of both thread 6 and thread 7 lines 307 358 Both threads have a priority of 8 which makes them the fifth and sixth threads in the demonstration system to execute The processing for each thread is the same incrementing its counter getting mutex 0 twice sleeping for 2 timer ticks releasing mutex 0 twice and repeating the sequence Notice that each thread suspends whenever mutex 0 is unavailable line 325 Also both threads use the same function for their main processing This presents no problems because they both have their own unique stack and C is naturally reentrant Each thread determines which one it is by examination of the thread input parameter line 319 which is setup when they are created lines 126 and 133 Demonstration Each of the demonstration threads increments its own unique counter The following counters may be examined to check on the demo s operation thread 0 counter thread 1 counter thread 2 counter thread 3 counter thread 4 counter thread 5 counter thread 6 counter ES User Guide Distribution file demo c 245 thread 7 counter
179. ng these files into the application development area Using ThreadX Using ThreadX is easy Basically the application code must include tx api h during compilation and link with the ThreadX run time library tx a The easiest way to create a new ThreadX based Express Logic Inc 34 0 0 00 Installation and Use of ThreadX application is to use MULTI s new project wizard See the MULTI documentation for detailed instructions When creating the project be sure to select ThreadX as the Operating System on the first pane of the new project wizard You should also choose a board that is similar to the one you will be using You can specify various other options including the location of your ThreadX distribution When the wizard completes you will have either a demonstration program or a simple framework project ready to edit In general there are four steps required to build a ThreadX application Include the tx api h file in all application files that use ThreadX services or data structures Create the standard C main function This function must eventually call tx kernel enter to start ThreadX Application specific initialization that does not involve ThreadX may be added prior to calling tx kernel enter The ThreadX entry function tx kernel enter does not return Make certain that you do not place any processing or function calls after it Create the tx application define function This is where the initial
180. nt This ULONG represents the number of created application timers tx timer thread stack area This character array allocates space for the System timer s stack The size of the array is defined by TX TIMER THREAD STACK SIZE and the tx timer stack start and tx timer stack end pointers point to the beginning and end of this array TX TA C This file contains tx timer activate which is responsible for processing all timer activate requests thread sleeps time outs and application timers Express Logic Inc 278 TX TAA C TX TD C TX TDA C TX TIMCH C TX TIMCR C TX TIMD C TX TIMEG C TX TIMES C Internal Composition of ThreadX This file contains tx timer activate api which is responsible for processing application timer activate requests This file contains tx timer deactivate which is responsible for processing all timer deactivate requests time outs and application timers This file contains tx timer deactivate api which is responsible for processing application timer deactivate requests This file contains tx timer change which is responsible for processing application timer change requests This file contains tx timer create which is responsible for processing application timer create requests This file contains tx timer delete which is responsible for processing application timer delete requests This file contains tx time get which is responsible for processing r
181. nt use of a deleted pool or its former memory blocks It is the application s responsibility to manage the memory area Input Parameters pool ptr Pointer to a previously created memory block pool Return Values TX SUCCESS 0x00 Successful memory block pool deletion TX POOL ERROR 0x02 Invalid memory block pool pointer TX CALLER ERROR 0x13 Invalid caller of this service Allowed From Threads Preemption Possible Yes ELITSE gt User Guide Memory Blocks 99 Example TX BLOCK POOL my pool UINT status Delete entire memory block pool Assume that the pool has already been created with a call to tx block pool create status tx block pool delete amp my pool If status equals TX SUCCESS the memory block pool is deleted See Also tx block allocate tx block pool create tx block pool info get tx block pool prioritize tx block release Express Logic Inc 100 Description of ThreadX Services tx block pool info get Prototype Retrieve information about block pool UINT tx block pool info get BLOCK POOL pool ptr CHAR name ULONG available ULONG total blocks TX THREAD first suspended ULONG suspended count TX BLOCK POOL next pool Description This service retrieves information about the specified block memory pool Input Parameters pool ptr name available total blocks first suspended suspended count next pool Return
182. o signal when to resetthe tx timer current ptr to the beginning of the tx timer list tx timer current ptr This TX INTERNAL TIMER head pointer points to an active timer list in the tx timer list array If a timer interrupt occurs and this entry is non NULL one or more timers have possibly expired This pointer is positioned to point at the next timer list head pointer after each timer interrupt tx timer expired This UINT flag is set in the timer ISR when a timer has expired It is cleared in the timer system thread after the expiration has been processed tx timer thread This TX THREAD structure is the control block for the internal timer thread This thread is setup during initialization and is used to process all timer expirations tx timer stack start This VOID pointer represents the starting address of the internal timer thread s stack ERIS User Guide Timer Component 277 tx timer stack size This ULONG represents the size of the internal timer thread s stack This variable contains the value specified by TX TIMER THREAD STACK SIZE which is defined inside of tx port h or on the command line tx timer priority This UINT represents the priority of the internal timer thread tx timer created ptr This TX TIMER pointer is the head pointer of the created application timer list The list is a doubly linked circular list of all created timer control blocks tx timer created cou
183. o the name of the thread entry function Specifies the initial C function for thread execution When a thread returns from this entry function it is placed in a completed state and suspended indefinitely entry input A 32 bit value that is passed to the thread s entry function when it first executes The use for this input is determined exclusively by the application stack start Starting address of the stack s memory area stack size Number bytes in the stack memory area The thread s stack area must be large enough to handle its worst case function call nesting and local variable usage priority Numerical priority of thread Legal values range from 0 through 31 where a value of 0 represents the highest priority ERIS User Guide Thread Control 177 preempt threshold time slice auto start i Highest priority level 0 31 of disabled preemption Only priorities higher than this level are allowed to preempt this thread This value must be less than or equal to the specified priority A value equal to the thread priority disables preemption threshold Number of timer ticks this thread is allowed to run before other ready threads of the same priority are given a chance to run Note that using preemption threshold disables time slicing Legal time slices selections range from 1 through OxFFFFFFFF A value of TX NO TIME SLICE a value of 0 disables time slicing of this thread Using time slicing results in a slig
184. oftware developer The developer should be familiar with standard real time operating system functions and the C programming language Organization Chapter 1 Provides a basic overview of ThreadX and its relationship to real time embedded development Chapter 2 Gives the basic steps to install and use ThreadX in your application right out of the box Chapter 3 Describes in detail the functional operation of ThreadX the high performance real time kernel Chapter 4 Details the application s interface to ThreadX Chapter 5 Describes writing I O drivers for ThreadX applications Chapter 6 Describes the demonstration application that is supplied with every ThreadX processor support package el gt User Guide 18 ThreadX Chapter 7 Appendix Appendix B Appendix C Appendix D Appendix E Index Guide Conventions Italics Boldface i N TID User Guide Details the internal construction of ThreadX ThreadX API ThreadX constants ThreadX data types ThreadX source files ASCII chart Topic cross reference typeface denotes book titles emphasizes important words and indicates variables typeface denotes file names key words and further emphasizes important words and variables Information symbols draw attention to important or additional information that could affect performance or function Warning symbols draw attention to situations in which developers should take care to avoid be
185. ointer to destination for the number of threads currently suspended on this semaphore Pointer to destination for the pointer of the next created semaphore TX SUCCESS 0x00 Successful semaphore information retrieval TX SEMAPHORE ERROR Ox0C Invalid semaphore pointer TX PTR ERROR ERIS User Guide 0x03 Invalid pointer NULL for any destination pointer Counting Semaphores 171 Allowed From Initialization threads timers and ISRs Preemption Possible No Example TX SEMAPHORE my semaphore CHAR name ULONG current value TX THREAD first suspended ULONG suspended count TX SEMAPHORE next semaphore UINT status Retrieve information about a the previously created semaphore my semaphore status tx semaphore info get amp my semaphore amp name amp current value amp first suspended amp suspended count amp next semaphore If status equals TX SUCCESS the information requested is valid See Also tx semaphore create tx semaphore delete tx semaphore get tx semaphore prioritize tx semaphore put Express Logic Inc 172 Description of ThreadX Services tx semaphore prioritize Prioritize semaphore suspension list Prototype UINT tx semaphore prioritize TX SEMAPHORE semaphore ptr Description This service places the highest priority thread suspended for an instance of the semaphore at the front of the suspension list All other threads remain in t
186. ool control blocks can also be located anywhere in memory but it is most common to make the control block a global structure by defining it outside the scope of any function Although memory byte pools provide the most flexible memory allocation they also suffer from somewhat un deterministic behavior For example a memory byte pool may have 2 000 bytes of memory available but may not be able to satisfy an allocation request of 1 000 bytes This is because there are no guarantees on how many of the free bytes are contiguous Even if a 1 000 byte free block exits there are no guarantees on how long it might take to find the block It is completely possible that the entire memory pool would need to be searched in order to find the 1 000 byte block Because of this it is generally good practice to avoid using memory byte services in areas where deterministic real time behavior is required Many applications pre allocate their required memory during initialization or run time configuration It is very important to insure that the user of allocated memory does not write outside its boundaries If this happens corruption occurs in an adjacent usually subsequent memory area The results are unpredictable and quite often fatal EIS User Guide Application Timers 83 Application Timers Timer Intervals Fast response to asynchronous external events is the most important function of real time embedded applications However many o
187. ool has already been created with a call to tx block pool create Status tx block allocate amp my pool VOID amp memory ptr TX NO WAIT If status equals TX SUCCESS memory ptr contains the address of the allocated block of memory See Also tx block pool create tx block pool delete tx block pool info get tx block pool prioritize tx block release Express Logic Inc 96 Description of ThreadX Services tx block pool create Create a pool of fixed size memory blocks Prototype UINT tx block pool create TX BLOCK POOL pool ptr CHAR name ptr ULONG block size VOID pool start ULONG pool size Description This service creates a pool of fixed size memory blocks The memory area specified is divided into as many fixed size memory blocks as possible using the formula total blocks total bytes block size sizeof void the user and is represented by the sizeof void in the preceding Each memory block contains one pointer of overhead that is invisible to I formula Input Parameters pool ptr Pointer to a memory block pool control block name ptr Pointer to the name of the memory block pool block size Number of bytes in each memory block pool start Starting address of the memory block pool pool size Total number of bytes available for the memory block pool ELITS a gt User Guide Memory Blocks 97 Return Values TX SUCCESS 0x00 Successful memory block pool c
188. opment tool specific When the development tool initialization is complete control transfers to the user supplied main function At this point the application controls what happens next For most applications the main function simply calls tx kernel enter which is the entry into ThreadX However applications can perform preliminary processing usually for hardware initialization prior to entering ThreadX The call to tx kernel enter does not return so don t place any processing after it The entry function coordinates initialization of various internal ThreadX data structures and then calls the application s definition function tx application define Express Logic Inc 50 Application Definition Function Interrupts Functional Components of ThreadX When tx application define returns control is transferred to the thread scheduling loop This marks the end of initialization The tx application define function defines all of the initial application threads queues semaphores mutexes event flags memory pools and timers It is also possible to create and delete system resources from threads during the normal operation of the application However all initial application resources are defined here The tx application define function has a single input parameter and it is certainly worth mentioning The first available RAM address is the sole input parameter to this function It is typically used as a start
189. option is often used to clear event flags in a group Otherwise if TX OR is specified the specified event flags are ORed with the current event in the group Return Values TX SUCCESS 0x00 Successful event flag set TX GROUP ERROR 0x06 Invalid pointer to event flags group TX OPTION ERROR 0x08 Invalid set option specified el gt User Guide Event Flags 131 Allowed From Initialization threads timers and ISRs Preemption Possible Yes Example TX EVENT FLAGS GROUP my event flags group UINT status Set event flags 0 4 and 8 status tx event flags set amp my event flags group 0x111 TX OR If status equals TX SUCCESS the event flags have been set and any suspended thread whose request was satisfied has been resumed See Also tx event flags create tx event flags delete tx event flags get tx event flags info get Express Logic Inc 132 Description of ThreadX Services tx interrupt control Enables and disables interrupts Prototype UINT tx interrupt control UINT new posture Description This service enables or disables interrupts as specified by the input parameter new posture remains part of that thread s context For example if the thread calls this routine to disable interrupts and then suspends when it is resumed interrupts are disabled again If this service is called from an application thread the interrupt posture This service should not be used
190. or handling the transmit complete interrupt Processing of the output ISR amounts to setting the output semaphore thereby allowing output of another character Express Logic Inc 230 IIO Drivers for ThreadX 4 Only threads are allowed to call the I tx sdriver output function Figure 11 shows the source code associated with simple driver output VOID tx sdriver output UCHAR alpha Determine if the hardware is ready to transmit a character If not suspend until the previous output completes tx semaphore get amp tx sdriver output semaphore TX WAIT FOREVER Send the character through the hardware serial hardware output ptr alpha VOID tx sdriver output ISR VOID Notify thread last character transmit is complete tx semaphore put amp tx sdriver output semaphore FIGURE 11 Simple Driver Output Simple Driver This simple I O driver example illustrates the basic Shortcomings idea of a ThreadX device driver However because the simple I O driver does not address data buffering or any overhead issues it does not fully represent real world ThreadX drivers The following section describes some of the more advanced issues associated with I O drivers ERIS User Guide Advanced Driver Issues 231 Advanced Driver Issues As mentioned previously I O drivers have requirements as unique as their applications Some applications may require an enormous amount of data buffering while anot
191. or initializing all of the component s internal global C data In addition all component global data instantiation takes place inside of the component s initialization file This is accomplished with conditional compilation in the component s specification file as well as a special define in its initialization file If none of the component s services are used by the application only the component s small initialization function is included in the application s run time image A variable number of the component body or action functions complete the composition of a ThreadX software component As a general rule component body functions are the only functions allowed to access the global data of the component All interaction with other components must use access functions defined in the other component s specification file Coding Conventions All ThreadX software conforms to a strict set of coding conventions This makes it easier to understand and maintain In addition it provides a reasonable template for application software conventions el gt User Guide ThreadX File Names ThreadX Name Space Coding Conventions 261 All ThreadX C file names take the form TX c x C where c represents the first initial letter of the component and x represents a variable number of supplemental initial letters used to identify the function contained in the file For example file tx tc c contains the function tx thread crea
192. ough demo bid is a simple example it provides a good template for real application development Once again please refer to the distribution s Express Start Guide and readme txt file for additional details TETTES User Guide Troubleshooting 37 Troubleshooting 0 Each ThreadX port is delivered with a demonstration application It is always a good idea to get the demonstration system running first either on actual target hardware or the specific demonstration environment simulator and or evaluation board Use the demo bld project to build the demonstration and download it to the target as described in the previous section If all the thread counters thread 0 counter through thread 7 counter continuously increment the demonstration is working correctly If not the following troubleshooting steps will help isolate the problem Is the download successful If the download fails check to make sure the addresses specified in demo ld are valid for the target hardware If the system runs such that all threads execute once but only threads 1 and 2 continue to run then the periodic timer interrupt is not working Check the readme txt file for information about the ThreadX timer interrupt If the system crashes or exhibits very strange behavior stack overflow could be present In such cases increasing stack sizes is generally a good idea Stack usage can be checked with the ThreadX debugging features found in the Green
193. p Prototype UINT tx event flags create TX EVENT FLAGS GROUP group ptr CHAR name ptr Description This service creates a group of 32 event flags All 32 event flags in the group are initialized to zero Each event flag is represented by a single bit Input Parameters group ptr Pointer to an event flags group control block name ptr Pointer to the name of the event flags group Return Values TX SUCCESS 0x00 Successful event group creation TX GROUP ERROR 0x06 Invalid event group pointer Either the pointer is NULL or the event group is already created TX CALLER ERROR 0x13 Invalid caller of this service Allowed From Initialization and threads Preemption Possible No ELITSE gt User Guide Event Flags 121 Example TX EVENT FLAGS GROUP my event group UINT status Create an event flag group status tx event flags create amp my event group my event group name If status equals TX SUCCESS my event flag group is ready for get and set services See Also tx event flags delete tx event flags get tx event flags info get tx event flags set Express Logic Inc 122 Description of ThreadX Services tx event flags delete Delete an event flag group Prototype UINT tx event flags delete TX EVENT FLAGS GROUP group ptr Description This service deletes the specified event flag group All threads suspended waiting for events from this group are resumed and given
194. ponent name For example the current thread pointer is part of the thread control component and is named tx thread current ptr and defined in the file tx thr h Readability is the only requirement imposed on local data elements i e data defined inside of ThreadX C functions The most frequently used of these elements are typically assigned the register modifier if supported by the target compiler All ThreadX component function names have the form tx c name Express Logic Inc 264 Source Code Indentation Comments Internal Composition of ThreadX ThreadX functions are in lower case where the c represents the entire component name For example the function that creates new application threads is named tx thread create The standard indentation increment in ThreadX Source code is four spaces Tab characters are avoided in order to make the source code less sensitive to text editors In addition the source code is also designed to use indentation and white space for greater readability In general each C statement in the ThreadX source code has a meaningful comment Each source file also contains a comment header that contains a description of the file revision history and the component it belongs to Figure 16 on page 265 shows the file header for the thread create file tx tc c ELITS a gt User Guide Coding Conventions Hd ThreadX Component Thread Control THR
195. priority 20 only interacts with a group of threads that have priorities between 15 and 20 During its critical sections the thread of priority 20 can set its preemption threshold to 15 thereby preventing preemption from all of the threads that it interacts with This still permits really important threads priorities between 0 and 14 to preempt this thread during its critical section processing which results in much more responsive processing Of course it is still possible for a thread to disable all preemption by setting its preemption threshold to O In addition preemption thresholds can be changed during run time Note that using preemption threshold disables time slicing for the specified thread ERIS User Guide Priority Inheritance Thread Creation Thread Control Block TX THREAD Thread Execution 57 ThreadX also supports optional priority inheritance within its mutex services described later in this chapter Priority inheritance allows a lower priority thread to temporarily assume the priority of a high priority thread that is waiting for a mutex owned by the lower priority thread This capability helps the application to avoid un deterministic priority inversion by eliminating preemption of intermediate thread priorities Of course preemption threshold may be used to achieve a similar result Application threads are created during initialization or during the execution of other application threads There ar
196. ptable by another thread Note that ISRs are not prevented by preemption disabling See Also tx thread create tx thread delete tx thread identify tx thread info get tx thread priority change tx thread relinquish tx thread resume tx thread sleep tx thread suspend tx thread terminate tx thread time slice change tx thread wait abort Express Logic Inc 190 Description of ThreadX Services tx thread priority change Change priority of an application thread Prototype UINT tx thread priority change TX THREAD thread ptr UINT new priority UINT old priority Description This service changes the priority of the specified thread Valid priorities range from 0 through 31 where 0 represents the highest priority level the new priority If a new threshold is desired the The preemption threshold of the specified thread is automatically set to I tx thread preemption change service must be used after this call Input Parameters thread ptr Pointer to a previously created application thread new priority New thread priority level 0 31 old priority Pointer to a location to return the thread s previous priority Return Values TX SUCCESS 0x00 Successful priority change TX THREAD ERROR 0x0E Invalid application thread pointer TX PRIORITY ERROR 0x0F Specified new priority is not valid a value other than 0 31 TX PTR ERROR 0x03 Invalid pointer to previous priority storage location
197. r input and output notifications Like other ThreadX interrupt service routines the low level handler must call tx thread context save before calling the simple driver ISR After the driver ISR returns the low level handler must call tx thread context restore It is important that initialization is called before any of the other driver functions Typically driver initialization is called from tx application define See Figure 9 on page 228 for the initialization source code of the simple driver Express Logic Inc 228 IIO Drivers for ThreadX VOID tx sdriver initialize VOID Initialize the two counting semaphores used to control the simple driver I 0 tx semaphore create amp tx sdriver input semaphore simple driver input semaphore 0 tx semaphore create amp tx sdriver output semaphore simple driver output semaphore 1 Setup interrupt vectors for input and output ISRs The initial vector handling should call the ISRs defined in this file Configure serial device hardware for RX TX interrupt generation baud rate stop bits etc FIGURE 9 Simple Driver Initialization Simple Driver Input for the simple driver centers around the input Input semaphore When a serial device input interrupt is received the input semaphore is set If one or more threads are waiting for a character from the driver the thread waiting the longest is resumed If no threads are waiting the semaphore simply
198. rable to that of simple linked list manipulation Furthermore memory block allocation and de allocation is done at the head of the available list This provides the fastest possible linked list processing and might help keep the actual memory block in cache Lack of flexibility is the main drawback of fixed size memory pools The block size of a pool must be large enough to handle the worst case memory requirements of its users Of course memory may be wasted if many different size memory requests are made to the same pool A possible solution is to make several different memory block pools that contain different sized memory blocks Each memory block pool is a public resource ThreadX places no constraints on how pools are used Memory block pools are created either during initialization or during run time by application threads There are no limits on the number of memory block pools in an application Express Logic Inc 78 Memory Block Size if Pool Capacity Pool s Memory Area Thread Suspension Functional Components of ThreadX As mentioned earlier memory block pools contain a number of fixed size blocks The block size in bytes is specified during creation of the pool ThreadX adds a small amount of overhead the size of a C pointer to each memory block in the pool In addition ThreadX might have to pad the block size in order to keep the beginning of each memory block on proper alignment
199. read 4 Threads of equal priority execute in a FIFO fashion Express Logic Inc 242 Thread 0 Thread 1 Thread 2 Demonstration System for ThreadX The function thread 0 entry marks the entry point of the thread lines 167 190 Thread 0 is the first thread in the demonstration system to execute Its processing is simple it increments its counter sleeps for 10 timer ticks sets an event flag to wake up thread 5 then repeats the sequence Thread 0 is the highest priority thread in the system When its requested sleep expires it will preempt any other executing thread in the demonstration The function thread 1 entry marks the entry point of the thread lines 193 216 Thread 1 is the second to last thread in the demonstration system to execute Its processing consists of incrementing its counter sending a message to thread 2 through queue 0 and repeating the sequence Notice that thread 1 suspends whenever queue 0 becomes full line 207 The function thread 2 entry marks the entry point of the thread lines 219 243 Thread 2 is the last thread in the demonstration system to execute Its processing consists of incrementing its counter getting a message from thread 1 through queue 0 and repeating the sequence Notice that thread 2 suspends whenever queue 0 becomes empty line 233 Although thread 1 and thread 2 share the lowest priority in the demonstration system priority 16 they el gt User Guide
200. read Create Thread Delete Thread Initialize Thread Identify Thread Information Get Thread Preemption Change Thread Priority Change Thread Resume Thread Resume API Thread Relinquish Thread Suspend API Thread Shell Entry Thread Sleep Thread Suspend Thread Terminate Thread Time out Thread Time Slice Thread Time slice Change Thread Wait Abort Thread Create Error Checking Thread Delete Error Checking Thread Information Get Error Checking Thread Preemption Change Error Checking el gt User Guide ThreadX C Source Files 321 TXE TRA C TXE TREL C TXE TRPC C TXE TSA C TXE TT C TXE TTSC C TXE TWA C Thread Resume API Error Checking Thread Relinquish Error Checking Thread Priority Change Error Checking Thread Suspend API Error Checking Thread Terminate Error Checking Thread Time slice Change Error Checking Thread Wait Abort Error Checking Express Logic Inc 322 ThreadX Source Files ThreadX Port Specific Assembly Language Files TX ILL S ASM SRC TX TCR S ASM SRC TX TCS S ASM SRC TX TIC S ASM SRC TX TIMIN S ASM SRC TX_TPC S ASM SRC TX TS S ASM SRC TX TSB S ASM SRC TX TSR S ASM SRC TID User Guide Initialize Low Level Thread Contest Restore Thread Context Save Thread Interrupt Control Timer Interrupt Handling Thread Preempt Check optional Tread Scheduler Thread Stack Build Thread System Return ASCII Character Codes m ASCII Character Codes in HEX
201. reation TX POOL ERROR 0x02 Invalid memory block pool pointer Either the pointer is NULL or the pool is already created TX PTR ERROR 0x03 Invalid starting address of the pool TX SIZE ERROR 0x05 Size of pool is invalid TX CALLER ERROR 0x13 Invalid caller of this service Allowed From Initialization and threads Preemption Possible No Example TX BLOCK POOL my pool UINT status Create a memory pool whose total size is 1000 bytes Starting at address 0x100000 Each block in this pool is defined to be 50 bytes long Status tx block pool create amp my pool my pool name 50 VOID 0x100000 1000 If status equals TX SUCCESS my pool contains 18 memory blocks of 50 bytes each The reason there are not 20 blocks in the pool is because of the one overhead pointer associated with each block See Also tx block allocate tx block pool delete tx block pool info get tx block pool prioritize tx block release Express Logic Inc 98 Description of ThreadX Services tx block pool delete Delete fixed size block of memory pool Prototype UINT tx block pool delete TX BLOCK POOL pool ptr Description This service deletes the specified block memory pool All threads suspended waiting for a memory block from this pool are resumed and given a TX DELETED return status associated with the pool which is available after this service completes In addition the application must preve
202. remains set until a thread calls the drive input function There are several limitations to the simple driver input handling The most significant is the potential for dropping input characters This is possible because there is no ability to buffer input characters that arrive before the previous character is processed This is easily handled by adding an input character buffer Only threads are allowed to call the I tx sdriver input function ERIS User Guide Simple Driver Example 229 Figure 10 shows the source code associated with simple driver input UCHAR tx sdriver input VOID Determine if there is a character waiting If not suspend tx semaphore get amp tx sdriver input semaphore TX WAIT FOREVER Return character from serial RX hardware register return serial hardware input ptr VOID tx sdriver input ISR VOID See if an input character notification is pending if tx sdriver input semaphore tx semaphore count If not notify thread of an input character tx semaphore put amp tx sdriver input semaphore FIGURE 10 Simple Driver Input Simple Driver Output processing utilizes the output semaphore to Output signal when the serial device s transmit register is free Before an output character is actually written to the device the output semaphore is obtained If it is not available the previous transmit is not yet complete The output ISR is responsible f
203. rent flags TX THREAD first suspended ULONG suspended count TX EVENT FLAGS GROUP next group UINT status Retrieve information about a the previously created event flag group my event group status tx event flags info get amp my event group amp name amp current flags amp first suspended amp suspended count amp next group If status equals TX SUCCESS the information requested is valid See Also tx event flags create tx event flags delete tx event flags get tx event flags set Express Logic Inc 130 Description of ThreadX Services tx event flags set Set event flags in an event flag group Prototype UINT tx event flags set EVENT FLAGS GROUP group ptr ULONG flags to set UINT set option Description This service sets or clears event flags in an event flag group depending upon the specified set option All suspended threads whose event flag request is now satisfied are resumed Input Parameters group ptr Pointer to the previously created event flag group control block flags to set Specifies the event flags to set or clear based upon the set option selected set option Specifies whether the event flags specified are ANDed or ORed into the current event flags of the group The following are valid selections TX AND 0x02 TX OR 0x00 Selecting TX AND specifies that the specified event flags are ANDed into the current event flags in the group This
204. rhead 26 81 associated with multi threaded kernels 26 reducing 26 overview 240 ThreadX 22 overwriting memory blocks 79 82 own 70 72 ownership count 73 P packet I O 231 path for the development tools 33 periodic interrupt source 30 periodic timer interrupt 37 periodic timer interrupt source 31 periodic timers 83 periodics 46 physical memory 48 picokernel 22 23 picokernel architecture 22 pitfall 72 74 polling 26 226 pool capacity 78 80 pool memory area 78 81 portability 23 27 PowerPC reset 36 preempt 56 preemption 55 preemption thresholds 56 57 63 64 72 preemptive scheduling 25 premium package 31 principal design elements of ThreadX 256 Prior to real time kernels 25 priorities 58 priority 54 priority ceiling 56 priority inheritance 57 63 73 74 priority inversion 56 62 63 72 74 priority overhead 64 priority zero 85 priority based scheduling 25 process 24 process oriented 24 processing bandwidth 62 88 processor allocation 27 processor allocation logic 27 processor isolation 26 processor reset 44 processor independent 26 producer consumer 69 product distribution 31 protecting the software investment 27 public resource 65 68 72 77 80 83 Q queue component 280 queue control 67 queue memory area 66 queue messages 52 queues 48 50 259 R RAM 47 59 67 RAM requirements 30 readme txt 30 31 37 38 40 87 ready 52 ready state 52 ready thread 44 r
205. river Access Some I O drivers are called only from a single application thread In such cases this functional area is not needed However in applications where multiple threads need simultaneous driver access their interaction must be controlled by adding assign release facilities in the I O driver Alternatively the application may use a semaphore to control driver access and avoid extra overhead and complication inside the driver Driver Input This functional area is responsible for all device input The principle issues associated with driver input usually involve how the input is buffered and how threads wait for such input Driver Output This functional area is responsible for all device output The principle issues associated with driver output usually involve how the output is buffered and how threads wait to perform output Express Logic Inc 226 Driver Interrupts Driver Status Driver Termination IIO Drivers for ThreadX Most real time systems rely on hardware interrupts to notify the driver of device input output control and error events Interrupts provide a guaranteed response time to such external events Instead of interrupts the driver software may periodically check the external hardware for such events This technique is called polling It is less real time than interrupts but polling may make sense for some less real time applications This function area is responsible for providing run tim
206. rvices UINT priority UINT preempt threshold ULONG time slice UINT auto start UINT tx thread delete TX THREAD thread ptr TX THREAD tx thread identify VOID UINT tx thread info get TX THREAD thread ptr CHAR name UINT state ULONG run count UINT priority UINT preemption threshold ULONG time slice TX THREAD next thread TX THREAD next suspended thread UINT tx thread preemption change TX THREAD thread ptr UINT new threshold UINT old threshold UINT tx thread priority change TX THREAD thread ptr UINT new priority UINT old priority VOID tx thread relinquish VOID UINT tx thread resume TX THREAD thread ptr UINT tx thread sleep ULONG timer ticks UINT tx thread suspend TX THREAD thread ptr UINT tx thread terminate TX THREAD thread ptr UINT tx thread time slice change TX THREAD thread ptr ULONG new time slice ULONG old time slice UINT tx thread wait abort TX THREAD thread ptr Time ULONG tx time get VOID VOID tx time set ULONG new time Services DUC Timer UINT tx timer activate TX TIMER timer ptr UINT tx timer change TIMER timer ptr Services ULONG initial ticks ULONG reschedule_ticks UINT tx timer create TX TIMER timer ptr CHAR name ptr VOID expiration function ULONG ULONG expiration input ULONG initial ticks ULONG reschedule ticks UINT auto activate UINT tx timer deactivate TX TIMER timer ptr UINT tx timer
207. s Logic Inc 308 ThreadX Constants TX NO MEMORY TX DELETE ERROR TX RESUME ERROR TX CALLER ERROR TX SUSPEND ERROR TX TIMER ERROR TX TICK ERROR TX ACTIVATE ERROR TX THRESH ERROR TX SUSPEND LIFTED TX WAIT ABORTED TX WAIT ABORT ERROR TX MUTEX ERROR TX NOT AVAILABLE TX NOT OWNED TX INHERIT ERROR TX MAX PRIORITIES TX WAIT FOREVER ELITS gt User Guide 0x0010 0x0011 0x0012 0x0013 0x0014 0x0015 0x0016 0x0017 0x0018 0X0019 0x001A 0x001B 0x001C 0x001D 0x001E 0x001F 32 FFFFFFFF APPENDIXC ThreadX Data Types lt TX INTERNAL TIMER 310 lt TX TIMER 310 lt TX QUEUE 310 lt TX THREAD 311 lt TX SEMAPHORE 312 TX EVENT FLAGS GROUP 312 lt TX BLOCK POOL 312 lt TX BYTE POOL 312 lt TX MUTEX 313 ERIS a gt User Guide 310 ThreadX Data Types typedef struct TX INTERNAL TIMER STRUCT ULONG tx remaining ticks ULONG tx re initialize ticks VOID tx timeout function ULONG ULONG tx timeout param struct TX INTERNAL TIMER STRUCT tx active next tx active previous struct TX INTERNAL TIMER STRUCT tx list head TX INTERNAL TIMER typedef struct TX TIMER STRUCT ULONG tx timer id CHAR PTR tx timer name TX INTERNAL TIMER tx timer internal struct TX TIMER STRUCT tx timer created next tx timer created previous TX TIMER typedef struct TX QUEUE STRUCT ULONG tx_queue_id C
208. s for errors This file contains txe semaphore put which is responsible for checking semaphore put requests for errors This file contains txe semaphore prioritize which is responsible for checking semaphore prioritize requests for errors Mutex Component TX MUT H This component is responsible for all mutex management activities including mutex creation deletion mutex gets and mutex puts This is the specification file for the ThreadX Mutex Component All component constants external interfaces and data structures are defined in this file Express Logic Inc 286 TX MC C TX MCLE C TX MD C TX MG C TX MI C Internal Composition of ThreadX The global data for the mutex component is defined in this file and consists of the following data elements tx mutex created ptr This TX MUTEX pointer is the head pointer of the created mutex list The list is a doubly linked circular list of all created mutex control blocks tx mutex created count This ULONG represents the number of created application mutexes This file contains tx mutex create which is responsible for processing mutex create requests This file contains tx mutex cleanup which is responsible for processing mutex suspension time outs mutex suspended thread termination and thread wait abort requests This file contains tx mutex delete which is responsible for processing mutex deletion requests This file contains
209. s is a little more difficult because the same program code can be executed from multiple threads In such cases a break point alone may not be enough The debugger must also view the current thread pointer tx thread current ptr to see if the calling thread is the one to debug Much of this is being handled in multi threading support packages offered through various development tool vendors Because of its simple design integrating ThreadX with different development tools is relatively easy Stack size is always an important debug topic in multi threading Whenever totally strange behavior is seen itis usually a good first guess to increase stack sizes for all threads especially the stack size of the last executing thread Message Queues Message queues are the primary means of inter thread communication in ThreadX One or more messages can reside in a message queue A message queue that holds a single message is commonly called a mailbox Messages are copied to a queue by tx queue send and are copied from a queue by fx queue receive The only exception to this is when a thread is suspended while waiting for a message on an empty queue In this case the next message sent to the queue is placed directly into the thread s destination area Each message queue is a public resource ThreadX places no constraints on how message queues are used Express Logic Inc 66 Creating Message Queues Message Size Mess
210. s that are received before the application software is ready Conversely an output buffer list is maintained for packets being sent faster than the hardware device can handle them Figure 15 on page 236 shows simple input and Express Logic Inc 236 IIO Drivers for ThreadX output linked lists of data packets and the buffer s that make up each packet Input List Input Head Pointer RE Packet 1 Packet 2 tx next packet tx next packet tx next packet tx next buffer tx next buffer tx next buffer Input Tail Pointer Packet n NULL tx buffer area tx buffer area tx buffer area more buffers in packet or NULL Output List Output Head Pointer Ne Packet 1 Packet 2 gt tx_next_packet tx next packet p tx next packet tx next buffer tx next buffer tx next buffer Output Tail Pointer Packet n NULL tx buffer area tx buffer area tx buffer area more buffers in packet or NULL FIGURE 15 Input Output Lists Applications interface with buffered drivers with the same I O buffers On transmit application software provides the driver with one or more buffers to transmit When the application software requests input the driver returns the input data in I O buffers In some applications it may be useful to build a I driver input interface that requires the application to exchange a free buffer for an input buffer from the EIS
211. s txe mutex prioritize which is responsible for checking mutex prioritize requests for errors Event Flag Component TX EVE H This component is responsible for all event flag management activities including event flag creation deletion setting and retrieval This is the specification file for the ThreadX Event Flags Component All component constants external interfaces and data structures are defined in this file The global data for the event flags component is defined in this file and consists of the following data elements tx event flags created ptr This TX EVENT FLAGS GROUP pointer is the head pointer of the created event flags list The list is a doubly linked circular list of all created event flags control blocks tx event flags created count This ULONG represents the number of created application event flags ERIS User Guide TX EFC C TX EFCLE C TX EFD C TX EFG C TX EFI C TX EFIG C TX EFS C TXE EFC C Event Flag Component 289 This file contains tx event flags create which is responsible for processing event flag create requests This file contains tx event flags cleanup which is responsible for processing event flag suspension time outs event flag suspended thread termination and thread wait abort requests This file contains tx event flags delete which is responsible for processing event flag deletion requests This file contains tx event flags get
212. se tx byte pool info get tx byte pool prioritize tx event flags info get tx event flags get el gt User Guide Interrupts 87 tx event flags set tx interrupt control tx queue front send tx queue info get tx queue prioritize tx queue receive tx queue send tx semaphore get tx semaphore info get tx semaphore prioritize tx semaphore put tx thread identify tx thread info get tx thread resume tx thread wait abort tx time get tx time set tx timer activate tx timer change tx timer deactivate tx timer info get Suspension is not allowed from ISRs Therefore special care must be made not to specify suspension in service calls made from ISRs ISR Template In order to manage application interrupts several ThreadX utilities must be called in the beginning and end of application ISRs The exact format for interrupt handling varies between ports Please review the readme txt file on the distribution disk for specific instructions on managing ISRs The following small code segment is typical of most ThreadX managed ISRs In most cases this processing is in assembly language Express Logic Inc 88 High Frequency Interrupts Interrupt Latency Functional Components of ThreadX application ISR entry Save context and prepare for ThreadX use by calling the ISR entry function CALL _ tx thread context save The ISR can now call ThreadX ervices and its own C functions
213. software The ThreadX library consists of 146 object files that are derived from 138 C source files and eight 8 processor specific assembly language files There are also ten C include files that are used in the C file compilation process All the C source and include files conform completely to the ANSI standard ThreadX applications need access to two include files tx api h and tx port h The tx api h file contains all the constants function prototypes and object data structures This file is generic i e it is the same for all processor support packages The fx port h file is included by tx api h It contains processor and or development tool specific information including data type assignments and interrupt management macros that are used throughout the ThreadX C source code The tx port h file also contains the ThreadX port specific ASCII version string tx version id The mapping of the ThreadX API services to the underlying error checking or core processing functions is done in tx api h Express Logic Inc 258 System Entry Application Definition il Internal Composition of ThreadX The ThreadX source package also contains eight 8 system include files These files represent the internal component specification files which are discussed later in this chapter From the application s point of view the entry point of ThreadX is the function tx_kernel_enter However this function is contained in
214. ssage is present Note that this suspension is only possible from application threads status tx queue receive amp my queue my message TX WAIT FOREVER If status equals TX SUCCESS the message is in my message See Also tx queue create tx queue delete tx queue flush tx queue front send tx queue info get tx queue prioritize tx queue send ELITSE gt User Guide Message Queues 161 Express Logic Inc 162 Description of ThreadX Services tx queue send Prototype Send a message to message queue UINT tx queue send TX QUEUE queue ptr VOID source ptr ULONG wait option Description This service sends a message to the specified message queue The sent message is copied to the queue from the memory area specified by the source pointer Input Parameters queue ptr source ptr wait option ERIS User Guide Pointer to a previously created message queue Pointer to the message Defines how the service behaves if the message queue is full The wait options are defined as follows TX NO WAIT 0x00000000 TX WAIT FOREVER OxFFFFFFFF timeout value 0x00000001 through OxFFFFFFFE Selecting TX_NO_WAIT results in an immediate return from this service regardless of whether or not it was successful This is the only valid option if the service is called from a non thread e g Initialization timer or ISR Selecting TX_WAIT_FOREVER causes the calling thread to susp
215. st applications the instruction image of ThreadX ranges between 2 KBytes and 15 KBytes in size What about performance Instead of layering kernel functions on top of each other like traditional microkernel architectures ThreadX services plug directly into its core This results in the fastest possible context switching and service call performance We call this non layering design a picokernel architecture ThreadX is written primarily in ANSI C A small amount of assembly language is needed to tailor the kernel to the underlying target processor This design makes it possible to port ThreadX to a new processor family in a very short time usually within weeks Most distributions of ThreadX include the complete C source code as well as the processor specific assembly language This eliminates the black box problems that occur with many commercial kernels By using ThreadX application developers can see ERIS User Guide A Potential Standard Embedded Applications 23 exactly what the kernel is doing there are no mysteries The source code also allows for application specific modifications Although not recommended it is certainly beneficial to have the ability to modify the kernel if it is absolutely required These features are especially comforting to developers accustomed to working with their own in house kernels They expect to have source code and the ability to modify the kernel ThreadX is the ultimate kerne
216. system resources are created Examples of system resources include threads queues memory pools event flag groups mutexes and semaphores Create a Green Hills MULTI build file that contains the ThreadX initialization file tx ill the application source files and the linker control file In addition the build file must be setup to use the previously built ThreadX library file tx a ERIS User Guide Small Example System 35 The supplied demonstration build file demo bld and linker control file demo ld may be used as templates Once the application s build file is created select the project BUILD button in the MULTI environment The resulting image can be executed on the target 0 To execute on the target the debugger must first be connected to the target This is accomplished by selecting the CONNECT button from the MULTI environment After the connection is complete the application can be downloaded and debugged by selecting the DEBUG button Small Example System Each ThreadX distribution contains a complete demonstration system that runs using MULTI s processor simulation or actual evaluation hardware The file demo c contains the demonstration source which is described in Chapter 5 To build the demonstration simply load demo bld and select the project BUILD button assuming the ThreadX library tx a has already been built with tx bld Once the ThreadX demonstration has been built it can be executed under
217. t comments expresslogic com Please type technical publication in the subject line rin d User Guide Introduction to ThreadX ThreadX is a high performance real time kernel designed specifically for embedded applications This chapter contains an introduction to the product and a description of its applications and benefits m ThreadX Unique Features 22 picokernel Architecture 22 ANSI C Source Code 22 Not A Black Box 22 A Potential Standard 23 m Embedded Applications 23 Real time Software 23 Multitasking 24 Tasks vs Threads 24 m ThreadX Benefits 25 Improved Responsiveness 25 Software Maintenance 26 Increased Throughput 26 Processor Isolation 26 Dividing the Application 27 Ease of Use 27 Improve Time to market 27 Protecting the Software Investment 27 el gt User Guide 22 Introduction to ThreadX ThreadX Unique Features picokernel Architecture ANSI C Source Code Not A Black Box Unlike other real time kernels ThreadX is designed to be versatile easily scaling among small micro controller based applications through those that use powerful RISC and DSP processors What makes ThreadX so scalable The reason is based on its underlying architecture Because ThreadX services are implemented as a C library only those services actually used by the application are brought into the run time image Hence the actual size of ThreadX is completely determined by the application For mo
218. t flags from a group Once an event flag is set the get requests of all suspended threads are reviewed All the threads that now have the required event flags are resumed It is important to emphasize that all suspended threads on an event flag group are reviewed when its event flags are set This of course introduces additional overhead Therefore it is generally good practice to limit the number of threads using the same event flag group to a reasonable number The characteristics of each event flag group are found in its control block It contains information such as the current event flag settings and the number of threads suspended for events This structure is defined in the tx api h file Event group control blocks can be located anywhere in memory but it is most common to make the control block a global structure by defining it outside the scope of any function ERIS User Guide Memory Block Pools 77 Memory Block Pools Creating Memory Block Pools Allocating memory in a fast and deterministic manner is always a challenge in real time applications With this in mind ThreadX provides the ability to create and manage multiple pools of fixed size memory blocks Since memory block pools consist of fixed size blocks there are never any fragmentation problems Of course fragmentation causes behavior that is inherently un deterministic In addition the time required to allocate and free a fixed size memory is compa
219. tate Understanding the different processing states of threads is a key ingredient to understanding the entire multi threaded environment In ThreadX there are five distinct thread states namely ready suspended executing terminated and completed Figure 5 on page 53 shows the thread state transition diagram for ThreadX A thread is in a ready state when it is ready for execution A ready thread is not executed until it is the highest priority thread ready When this happens ThreadX executes the thread which changes its state to executing If a higher priority thread becomes ready the executing thread reverts back to a ready state The newly ready high priority thread is then executed which changes its logical state to executing This transition between ready and executing states occurs every time thread preemption occurs It is important to point out that at any given moment only one thread is in an executing state This is because a thread in the executing state actually has control of the underlying processor Threads that are in a suspended state are not eligible for execution Reasons for being in a suspended state include suspension for time queue messages semaphores mutexes event flags memory and basic thread suspension Once the cause for suspension is removed the thread is placed back in a ready state EIS User Guide Thread Execution 53 tx thread create TX DONT START Scheduling Se
220. te tx block pool prioritize tx block release Express Logic Inc 102 Description of ThreadX Services tx block pool prioritize Prioritize block pool suspension list Prototype UINT tx block pool prioritize TX BLOCK POOL pool ptr Description This service places the highest priority thread suspended for a block of memory on this pool at the front of the suspension list All other threads remain in the same FIFO order they were suspended in Input Parameters pool ptr Pointer to a memory block pool control block Return Values TX SUCCESS 0x00 Successful block pool prioritize TX POOL ERROR 0x02 Invalid memory block pool pointer Allowed From Initialization threads timers and ISRs Preemption Possible No ELITSE gt User Guide Memory Blocks 103 Example TX BLOCK POOL my pool UINT status Ensure that the highest priority thread wi receive h he high i i h d will the next free block in this pool status tx block pool prioritize amp my pool If status equals TX SUCCESS the highest priority suspended thread is at the front of the list The next tx block release call will wake up this thread See Also tx block allocate tx block pool create tx block pool delete tx block pool info get tx block release Express Logic Inc 104 Description of ThreadX Services tx block release Release a fixed size block of memory Prototype UINT tx block release VOID bloc
221. te and file tx ike c contains the function tx initialize kernel enter Component specification file names are slightly different taking on the form TX ccc H where the ccc field represents the first three characters of the component s name For example the file tx tim h contains the timer component specification The file naming conventions make it easy to distinguish ThreadX files from all other application source files In a similar vein all ThreadX functions and global data have a leading tx in their name This keeps ThreadX global symbols separate from the application symbols and in one contiguous area of load map created by the linker Most development tools will insert an additional underscore in front of all global symbols For ANSI compliance and greater compiler compatibility all symbolic names in ThreadX are limited to 31 characters Express Logic Inc 262 ThreadX Constants ThreadX Struct and Typedef Names Internal Composition of ThreadX All ThreadX constants have the form TX NAME or TX C NAME and are comprised of capital letters numerics and underscores System constants defined in tx api h or tx port h take the form TX NAME For example the system wide constant associated with a successful service call return is TX SUCCESS Component constants defined in component specification files take on the form TX C NAME where C represents the capitalized entire component nam
222. tex control block name ptr Pointer to the name of the mutex priority inherit Specifies whether or not this mutex supports priority inheritance If this value is TX INHERIT then priority inheritance is supported However if TX NO INHERIT is specified priority inheritance is not supported by this mutex Return Values TX SUCCESS 0x00 Successful mutex creation TX MUTEX ERROR 0x1C Invalid mutex pointer Either the pointer is NULL or the mutex is already created TX CALLER ERROR 0x13 Invalid caller of this service TX INHERIT ERROR 0x1F Invalid priority inherit parameter Allowed From Initialization and threads Preemption Possible No el gt User Guide Mutex Example TX MUTEX my mutex UINT status 135 Create a mutex to provide protection over a common resource status tx mutex create amp my mutex my mutex name TX NO INHERIT If status equals TX SUCCESS my mutex is ready for use See Also tx mutex delete tx mutex get tx mutex info get tx mutex prioritize tx mutex put Express Logic Inc 136 Description of ThreadX Services tx mutex delete Delete a mutual exclusion mutex Prototype UINT tx mutex delete TX MUTEX mutex ptr Description This service deletes the specified mutex All threads suspended waiting for the mutex are resumed and given a TX DELETED return status It is the application s responsibility to prevent use of de
223. the highest priority thread suspended on a byte pool and moving it to the front of the suspension list This file contains tx byte release which is responsible for processing byte release requests This file contains tx byte pool search which is responsible for searching through the byte memory pool for a large enough area of free bytes Fragmented blocks are merged as the search proceeds through the memory area ERIS User Guide TXE BTYA C TXE BYTC C TXE BYTD C TXE BYTG C TXE BYTP C TXE BYTR C Byte Memory Component 295 This file contains txe byte allocate which is responsible for checking byte allocate requests for errors This file contains txe byte pool create which is responsible for checking byte memory pool create requests for errors This file contains txe byte pool delete which is responsible for checking byte memory pool delete requests for errors This file contains txe byte pool info get which is responsible for checking byte pool information retrieval requests for errors This file contains txe byte pool prioritize which is responsible for checking byte pool prioritize requests for errors This file contains txe byte release which is responsible for checking byte memory release requests for errors Express Logic Inc 296 Internal Composition of ThreadX TID User Guide APPENDIX ThreadX API Services m Entry Function 298 m Byte Memory Ser
224. the initial expiration status tx timer change amp my timer 50 50 If status equals TX SUCCESS the specified timer is changed to expire every 50 ticks Activate the specified timer to get it started again Status tx timer activate amp my timer See Also tx timer activate tx timer create tx timer deactivate tx timer delete tx timer info get Express Logic Inc 214 Description of ThreadX Services tx timer create Prototype Create an application timer UINT tx timer create TX TIMER timer ptr CHAR name ptr VOID expiration function ULONG Description ULONG expiration input ULONG initial ticks ULONG reschedule ticks UINT auto activate This service creates an application timer with the specified expiration function and periodic Input Parameters timer ptr name ptr expiration function expiration input initial ticks reschedule ticks auto activate el gt User Guide Pointer to a timer control block Pointer to the name of the timer Application function to call when the timer expires Input to pass to expiration function when timer expires Specifies the initial number of ticks for timer expiration Legal values range from 1 through OxFFFFFFFF Specifies the number of ticks for all timer expirations after the first A zero for this parameter makes the timer a one shot timer Otherwise for periodic timers legal values range from 1 through Ox
225. the initialization file so its real name is _tx_initialize_kernel_enter Typically this function is called from the application main routine with interrupts still disabled from the hardware reset and compiler start up processing The entry function is responsible for calling the processor specific low level initialization and the high level C initialization After all the initialization is complete this function transfers control to the ThreadX scheduling loop ThreadX applications are required to provide their own tx application define function This function is responsible for setting up the initial threads and other system objects This function is called from the high level C initialization mentioned previously Avoid enabling interrupts inside of the tx application define function If interrupts are enabled unpredictable results may occur Software Components Express Logic utilizes a software component methodology in its products A software component is somewhat similar to an object or class in C Each component provides a set of action functions that operate on the internal data of the component In general components are not allowed access to the ERIS User Guide il ThreadX Components Component Specification File Software Components 259 global data of other components The one exception to this rule is the thread component For performance reasons information like the currently running thread is access
226. thread its control block TX THREAD and stack can be placed in the fast memory area which might greatly enhance its performance Understanding the initialization process is very important The initial hardware environment is setup here In addition this is where the application is given its initial personality ThreadX attempts to utilize whenever possible the complete development tool s initialization process This makes it easier to upgrade to new versions of the development tools in the future ERIS User Guide System Reset Development Tool Initialization main i tx kernel enter Initialization 49 All microprocessors have reset logic When a reset occurs either hardware or software the address of the application s entry point is retrieved from a specific memory location After the entry point is retrieved the processor transfers control to that location The application entry point is quite often written in the native assembly language and is usually supplied by the development tools at least in template form In some cases a special version of the entry program is supplied with ThreadX After the low level initialization is complete control transfers to the development tool s high level initialization This is usually the place where initialized global and static C variables are setup Remember that their initial values are retrieved from the constant area Exact initialization processing is devel
227. to enable interrupts during initialization Doing so could cause unpredictable results Input Parameters new posture This parameter specifies whether interrupts are disabled or enabled Legal values include TX INT DISABLE and TX INT ENABLE The actual values for these parameters are port specific In addition some processing architectures might support additional interrupt disable postures Please see the readme txt information supplied on the distribution disk for more details Return Values previous posture This service returns the previous interrupt posture to the caller This allows users of the service to restore the previous posture after interrupts are disabled el gt User Guide Interrupt Control 133 Allowed From Threads timers and ISRs Preemption Possible No Example UINT my old posture Lockout interrupts my old posture tx interrupt control INT DISABLE Perform critical operations that need interrupts locked out Restore previous interrupt lockout posture tx interrupt control my old posture See Also None Express Logic Inc 134 Description of ThreadX Services tx mutex create Create a mutual exclusion mutex Prototype UINT tx mutex create TX MUTEX mutex ptr CHAR name ptr UINT priority inherit Description This service creates a mutex for inter thread mutual exclusion for resource protection Input Parameters mutex ptr Pointer to a mu
228. to memory pool Prototype UINT tx byte release VOID memory ptr Description This service releases a previously allocated memory area back to its associated pool If there are one or more threads suspended waiting for memory from this pool each suspended thread is given memory and resumed until the memory is exhausted or until there are no more suspended threads This process of allocating memory to suspended threads always begins with the first thread suspended The application must prevent using the memory area after it is released Input Parameters memory ptr Pointer to the previously allocated memory area Return Values TX SUCCESS 0x00 Successful memory release TX PTR ERROR 0x03 Invalid memory area pointer TX CALLER ERROR 0x13 Invalid caller of this service Allowed From Initialization and threads Preemption Possible Yes ELITSE gt User Guide Memory Bytes 119 Example unsigned char memory ptr UINT status Release a memory back to my pool Assume that the memory area was previously allocated from my pool status tx byte release VOID memory ptr If status equals TX SUCCESS the memory pointed to by memory ptr has been returned to the pool See Also tx byte allocate tx byte pool create tx byte pool delete tx byte pool info get tx byte pool prioritize Express Logic Inc 120 Description of ThreadX Services tx event flags create Create an event flag grou
229. turn from this service regardless of whether or not it was successful This is the only valid option if the service is called from a non thread e g Initialization timer or ISR Selecting TX WAIT FOREVER causes the calling thread to suspend indefinitely until there is room in the queue Selecting a numeric value 1 OxFFFFFFFE specifies the maximum number of timer ticks to stay suspended while waiting for room in the queue ERIS User Guide Message Queues 153 Return Values TX SUCCESS 0x00 Successful sending of message TX DELETED 0x01 Message queue was deleted while thread was suspended TX QUEUE FULL 0x0B Service was unable to send message because the queue was full TX WAIT ABORTED 0x1A Suspension was aborted by another thread timer or ISR TX QUEUE ERROR 0x09 Invalid message queue pointer TX PTR ERROR 0x03 Invalid source pointer for message TX WAIT ERROR 0x04 A wait option other than TX NO WAIT was specified on a call from a non thread Allowed From Initialization threads timers and ISRs Preemption Possible Yes Example TX QUEUE my queue UINT status ULONG my message 4 Send a message to the front of my queue Return immediately regardless of success This wait option is used for calls from initialization timers and ISRs status tx queue front send amp my queue my message TX NO WAIT status equals message is fron If stat ls TX SUCCESS th
230. tus 187 if status TX SUCCESS 188 break 189 190 191 192 193 void thread 1 entry ULONG thread input 194 195 196 UINT status 197 198 199 This thread simply sends messages to a queue shared by thread 2 200 while 1 201 202 203 Increment the thread counter 204 thread 1 counter 205 206 Send message to queue 0 207 status tx queue send amp queue 0 amp thread 1 messages sent TX WAIT FOREVER 208 209 Check completion status 210 if status TX SUCCESS 211 break 212 213 Increment the message sent 214 thread 1 messages sent 215 TETTES User Guide Distribution file demo c 249 216 217 218 219 void thread 2 entry ULONG thread input 220 221 222 ULONG received message 223 UINT status 224 225 This thread retrieves messages placed on the queue by thread 1 226 while 1 227 228 229 Increment the thread counter 230 thread 2 counter 231 232 Retrieve a message from the queue 233 status tx queue receive amp queue 0 amp received message TX WAIT FOREVER 234 235 Check completion status and make sure the message is what we 236 expected 237 if status TX SUCCESS received message thread 2 messages received 238 break 239 240 Otherwise all is okay Increment the received message count 241 thread 2 messages received 242 243 244 245 24
231. tx input read ptr if tx input read ptr gt amp tx input buffer MAX SIZE 1 SEE ESTONE FIGURE 12 Logic for Circular Input Buffer EIS User Guide Advanced Driver Issues 233 For reliable operation it may be necessary to lockout I interrupts when manipulating the read and write pointers of both the input and output circular buffers Circular Output The output buffer is used to hold characters that Buffer have arrived for output before the hardware device finished sending the previous byte Output buffer processing is similar to input buffer processing except the transmit complete interrupt processing manipulates the output read pointer while the application output request utilizes the output write pointer Otherwise the output buffer processing is the same Figure 13 shows the logic for the circular output buffer F recs UCHAR tx output buffer MAX SIZ UCHAR tx output write ptr UCHAR tx output read ptr Initialization tx output write ptr amp tx output buffer 0 TSEL amp tx output buffer 0 Transmit complete ISR Device ready to send if tx output read ptr tx output write ptr device reg tx output read ptr if tx output read reg amp tx output buffer MAX SIZE 1 tx output read ptr amp tx output buffer 0 Output byte driver service If device busy buffer Save ptr tx o
232. tx mutex get which is responsible for processing mutex get requests This file contains tx mutex initialize which is responsible for initialization of the mutex component el gt User Guide TX MIG C TX MP C TX MPC C TX MPRI C TXE MC C TXE MD C TXE MG C TXE MIG C Mutex Component 287 This file contains tx mutex info get which is responsible for mutex information retrieval requests This file contains tx mutex put which is responsible for mutex put requests This file contains tx mutex priority change which is used by the mutex priority inheritance logic to modify thread priorities This file contains tx mutex prioritize which is responsible for finding the highest priority thread suspended on a mutex and placing it at the front of the suspension list This file contains txe mutex create which is responsible for checking mutex create requests for errors This file contains txe mutex delete which is responsible for checking mutex delete requests for errors This file contains txe mutex get which is responsible for checking mutex get requests for errors This file contains txe mutex info get which is responsible for checking mutex information retrieval requests for errors Express Logic Inc 288 TXE MP C TXE MPRI C Internal Composition of ThreadX This file contains txe mutex put which is responsible for checking mutex put requests for errors This file contain
233. uctures are defined in this file The global data for the byte memory component is defined in this file and consists of the following data elements tx byte pool created ptr This TX BYTE POOL pointer is the head pointer of the created byte memory pool list The list is a doubly linked circular list of all created byte pool control blocks tx byte pool created count This ULONG represents the number of created application byte memory pools This file contains tx byte allocate which is responsible for processing byte memory allocation requests This file contains tx byte pool create which is responsible for processing byte memory pool create requests Express Logic Inc 294 TX BYTCL C TX BYTD C TX BYTI C TX BYTIG C TX BYTPP C TX BYTR C TX BYTS C Internal Composition of ThreadX This file contains tx byte pool cleanup which is responsible for processing byte memory suspension time outs byte memory suspended thread termination and thread wait abort requests This file contains tx byte pool delete which is responsible for processing byte memory pool delete requests This file contains tx byte pool initialize which is responsible for initialization of the byte memory pool component This file contains tx byte pool info get which is responsible for retrieving information about a byte pool This file contains tx byte pool prioritize which is responsible for finding
234. uspended FIFO However priority resumption is done automatically if the mutex priority inheritance was selected during creation In addition priority resumption is also possible if the application calls tx mutex prioritize prior to the mutex put call that lifts thread suspension The mutex prioritize service places the highest priority thread at the front of the suspension list while leaving all other suspended threads in the same FIFO order Express Logic Inc 74 Mutex Control Block TX MUTEX Deadly Embrace Priority Inversion Functional Components of ThreadX The characteristics of each mutex are found in its control block It contains interesting information such as the current mutex ownership count along with the pointer of the thread that owns the mutex This structure is defined in the tx api h file Mutex control blocks can be located anywhere in memory but it is most common to make the control block a global structure by defining it outside the scope of any function One of the most interesting and dangerous pitfalls associated with mutex ownership is the deadly embrace A deadly embrace or deadlock is a condition where two or more threads are suspended indefinitely while attempting to get a mutex already owned by the other threads The discussion of deadly embrace and its remedies found in the previous semaphore discussion is completely valid for the mutex object as well As mentioned previously a
235. ut Parameters pool ptr name available fragments first suspended suspended count next pool Return Values TX SUCCESS TX POOL ERROR TX PTR ERROR ERIS User Guide Pointer to previously created memory pool Pointer to destination for the pointer to the byte pool s name Pointer to destination for the number of available bytes in the pool Pointer to destination for the total number of memory fragments in the byte pool Pointer to destination for the pointer to the thread that is first on the suspension list of this byte pool Pointer to destination for the number of threads currently suspended on this byte pool Pointer to destination for the pointer of the next created byte pool 0x00 Successful pool information retrieve 0x02 Invalid memory pool pointer 0x03 Invalid pointer NULL for any destination pointer Memory Bytes 115 Allowed From Initialization threads timers and ISRs Preemption Possible No Example TX BYTE POOL my pool CHAR name ULONG available ULONG fragments TX THREAD first suspended ULONG suspended count TX BYTE POOL next pool UINT status Retrieve information about a the previously created block pool my pool status tx byte pool info get amp my pool amp name amp available amp fragments amp first suspended amp suspended count amp next pool If status equals TX SUCCESS the information requested is valid
236. utput write ptr tx output write ptr alpha if tx output write ptr gt amp tx output buffer MAX SIZE 1 tx output write ptr amp tx output buffer 0 Wrap if tx output write ptr tx output read ptr tx output write ptr save ptr Buffer full FIGURE 13 Logic for Circular Output Buffer Express Logic Inc 234 Drivers for ThreadX Buffer I O To improve the performance of embedded Management microprocessors many peripheral I O devices transmit and receive data with buffers supplied by software In some implementations multiple buffers may be used to transmit or receive individual packets of data The size and location of I O buffers is determined by the application and or driver software Typically buffers are fixed in size and managed within a ThreadX block memory pool Figure 14 describes a typical I O buffer and a ThreadX block memory pool that manages their allocation typedef struct TX IO BUFFER STRUCT struct TX IO BUFFER STRUCT tx next packet Struct TX BUPFER STRUCT next but ken UCHAR tx buffer area TX MAX BUFFER SIZE TX IO BUFFER TX BLOCK POOL tx io block pool Create a pool of I 0 buffers Assume that the pointer free memory ptr points to an available memory area that is 64KBytes in size tx block pool create amp tx io block pool Sample IO Driver Buffer Pool free memory ptr 0x10000 sizeof TX IO BUFFER FIGURE 14 I O Buffer TX IO BUFFER The type
237. vices 298 m Block Memory Services 298 em Event Flag Services 299 interrupt Control 299 m Message Queue Services 299 m Semaphore Services 300 m Mutex Services 300 m Thread Control Services 301 em Time Services 301 Timer Services 301 ERIS gt User Guide 298 Entry Function Byte Memory Services Block Memory Services VOID UINT UINT UINT UINT UINT UINT UINT UINT UINT UINT UINT UINT ThreadX API Services tx kernel enter VOID tx byte allocate TX BYTE POOL pool ptr VOID memory ptr ULONG memory size ULONG wait option tx byte pool create TX BYTE POOL pool ptr CHAR name ptr VOID pool start ULONG pool size tx byte pool delete TX BYTE POOL pool ptr tx byte pool info get TX BYTE POOL pool ptr CHAR name ULONG available bytes ULONG fragments TX THREAD first suspended ULONG suspended count TX BYTE POOL next pool tx byte pool prioritize TX BYTE POOL pool ptr tx byte release VOID memory ptr tx block allocate TX BLOCK POOL pool ptr VOID block ptr ULONG wait option tx block pool create TX BLOCK POOL pool ptr CHAR name ptr ULONG block size VOID pool start ULONG pool size tx block pool delete TX BLOCK POOL pool ptr tx block pool info get TX BLOCK POOL pool ptr CHAR name ULONG available blocks ULONG total blocks TX THREAD first suspended ULONG suspended count TX
238. which is responsible for processing event flag retrieval requests This file contains tx event flags initialize which is responsible for initialization of the event flags component This file contains tx event flags info get which is responsible for event flag information retrieval This file contains tx event flags set which is responsible for processing event flag setting requests This file contains txe event flags create which is responsible for checking event flags create requests for errors Express Logic Inc 290 Internal Composition of ThreadX TXE EFD C This file contains txe event flags delete which is responsible for checking event flags delete requests for errors TXE EFG C This file contains txe event flags get which is responsible for checking event flag retrieval requests for errors TXE EFIG C This file contains txe event flags info get which is responsible for checking event flag information retrieval requests for errors TXE EFS C This file contains txe event flags set which is responsible for checking event flag setting requests for errors Block Memory Component This component is responsible for all block memory management activities including block pool creation deletion block allocates and block releases TX BLO H This is the specification file for the ThreadX Block Memory Component All component constants external interfaces and data structures are d
239. x filex ptr TX THREAD typedef struct TX SEMAPHORE STRUCT ULONGtx semaphore id CHAR PTR tx semaphore name ULONG tx semaphore count struct TX THREAD STRUCT tx semaphore suspension list ULONG tx semaphore suspended count struct TX SEMAPHORE STRUCT tx semaphore created next Express Logic Inc 312 ThreadX Data Types tx semaphore created previous TX SEMAPHORE typedef struct TX EVENT FLAGS GROUP STRUCT ULONG tx event flags id CHAR PTR tx event flags name ULONG tx event flags current UINT tx event flags reset search struct TX THREAD STRUCT tx event flags suspension list ULONG tx event flags suspended count struct TX EVENT FLAGS GROUP STRUCT tx event flags created next tx event flags created previous TX EVENT FLAGS GROUP typedef struct TX BLOCK POOL STRUCT ULONG tx block pool id CHAR PTR tx block pool name ULONG tx block pool available ULONG tx block pool total CHAR PTR tx block pool available list CHAR PTR tx block pool start ULONG tx block pool size ULONG tx block pool block size struct TX THREAD STRUCT tx block pool suspension list ULONG tx block pool suspended count struct TX BLOCK POOL STRUCT tx block pool created next tx block pool created previous TX BLOCK POOL typedef struct TX BYTE POOL STRUCT ULONG tx byte pool id CHAR PTR tx byte pool name ULONG tx byte pool available ULON
240. xecute Note that using preemption threshold disables time slicing for the I specified thread Input Parameters thread_ptr Pointer to application thread new_time_slice New time slice value Legal values include TX_NO_TIME_SLICE and numeric values from 1 through OxFFFFFFFF old_time_slice Pointer to location for storing the previous time slice value of the specified thread Return Values TX_SUCCESS 0x00 Successful time slice chance TX_THREAD_ERROR 0x0E Invalid application thread pointer TX_PTR_ERROR 0x03 Invalid pointer to previous time slice storage location TX_CALLER_ERROR 0x13 Invalid caller of this service TID User Guide Thread Control 203 Allowed From Threads and timers Preemption Possible No Example TX THREAD my thread ULONG my old time slice UINT status Change the time slice of the thread associated with my thread to 20 This will mean that my thread can only run for 20 timer ticks consecutively before other threads of equal or higher priority get a chance to run status tx thread time slice change amp my thread 20 amp my old time slice If status equals TX SUCCESS the thread s time slice has been changed to 20 and the previous time slice is in my old time slice See Also tx thread create tx thread delete tx thread identify tx thread info get tx thread preemption change tx thread priority change tx thread relinquish tx thread resume
241. ynchronous change in processor execution Typically when an interrupt occurs the processor saves a small portion of the current execution on the stack and transfers control to the appropriate interrupt vector The interrupt vector is basically just the address of the routine responsible for handling the specific type interrupt The exact interrupt handling procedure is processor specific The tx interrupt control service allows applications to enable and disable interrupts The previous interrupt enable disable posture is returned by this service It is important to mention that interrupt control only affects the currently executing program segment For example if a thread disables interrupts they only remain disabled during execution of that thread A Non Maskable Interrupt NMI is defined as an interrupt that the cannot be disabled by the hardware Such an interrupt may be used by ThreadX applications However the application s NMI handling routine is not allowed to use ThreadX context management or any API services ThreadX provides applications with complete interrupt management This management includes saving and restoring the context of the interrupted execution In addition ThreadX allows certain services to be called from within Interrupt Service Routines ISRs The following is a list of ThreadX services allowed from application ISRs tx block allocate tx block pool info get tx block pool prioritize tx block relea
242. ze 79 86 tx block release 104 TX BPC C 291 TX BPCLE C 291 TX BPD C 291 TX BPI C 291 TX BPIG C 291 TX BPP C 292 TX BR C 292 TX BYT H 293 TX BYTA C 293 TX BYTC C 293 TX BYTCL C 294 TX BYTD C 294 tx byte allocate 106 114 TX BYTE MEMORY 0x09 58 TX BYTE POOL 82 tx byte pool create 110 116 Express Logic Inc 334 tx byte pool delete 112 tx byte pool info get 86 tx byte pool prioritize 81 86 tx byte release 118 TX BYTI C 294 TX BYTIG C 294 TX BYTPP C 294 TX BYTR C 294 TX BYTS C 294 TX COMPLETED 0x01 58 TX DISABLE ERROR CHECKING 38 39 257 TX DISABLE ERROR CHECKNG 89 TX DISABLE STACK CHECKING 38 TX EFC C 289 TX EFCLE C 289 TX EFD C 289 TX EFG C 289 TX EFI C 289 TX EFIG C 289 TX EFS C 289 TX ENABLE EVENT FILTERS 40 TX ENABLE EVENT LOGGING 39 TX ENABLE MULTI ERROR CHECKIN G 39 TX EVE H 288 TX EVENT FLAG 0x07 58 TX EVENT FLAG GROUP 76 tx event flags create 120 128 tx event flags delete 122 tx event flags get 75 86 124 tx event flags info get 86 tx event flags set 75 87 130 TX IHL C 266 tx ihl c 39 TX IKE C 266 tx ike c 261 TX ILL 267 tx ill 37 tx ill assembly file 30 83 TX INI H 266 TX INITIALIZE IN PROGRESS 262 tx interrupt control 86 87 TX IO BUFFER 234 TX IO DRIVER 0x0A 58 tx kernel enter 34 49 51 258 266 TETTES User Guide TX MC C 286 TX MIG C 287 TX MINIMUM STACK 59 TX MPC C 287 TX MPRI C 287 tx mut

Download Pdf Manuals

image

Related Search

Related Contents

5000W Fuel Cell Stack  BusyBox User Guide  9913680 1996-1998 Vol. II ATV Service Manual Chapter  Samsung DVD-C550 User Manual  Vente de terrains boisés, mode d`emploi  HYUNDAI SONATA HYBRID - Dealer e  Minolta Color PageWorks EX Plus Laser Printer  Franklin Merriam Webster MWD  CONTENTS  User interface having movable sheet with click  

Copyright © All rights reserved.
Failed to retrieve file