Texas Instruments TMS320 DSP manual Example

Page 18

www.ti.com

Threads and Reentrancy

The definition of reentrant code often implies that the code does not retain "state" information. That is, if you invoke the code with the same data at different times, by the same or other thread, it will yield the same results. This is not always true, however. How can a function maintain state and still be reentrant? Consider the rand() function. Perhaps a better example is a function with state that protects that state by disabling scheduling around its critical sections. These examples illustrate some of the subtleties of reentrant programming.

The property of being reentrant is a function of the threading model; after all, before you can determine whether multiple threads can use a particular function, you must know what types of threads are possible in a system. For example, if threads are not preemptive, a function may freely use global variables if it uses them for scratch storage only; i.e., it does not assume these variables have any values upon entry to the function. In a preemptive environment, however, use of these global variables must be protected by a critical section or they must be part of the context of every thread that uses them.

Although there are exceptions, reentrancy usually requires that algorithms:

only modify data on the stack or in an instance "object"

treat global and static variables as read-only data

never employ self modifying code

These rules can sometimes be relaxed by disabling all interrupts (and therefore, disabling all thread scheduling) around the critical sections that violate the rules above. Since algorithms are not permitted to directly manipulate the interrupt state of the processor, the allowed DSP/BIOS HWI module functions (or equivalent implementations) must be called to create these critical sections.

Rule 2

All algorithms must be reentrant within a preemptive environment (including time-sliced preemption).

2.2.4 Example

In the remainder of this section we consider several implementations of a simple algorithm, digital filtering of an input speech data stream, and show how the algorithm can be made reentrant and maintain acceptable levels of performance. It is important to note that, although these examples are written in C, the principles and techniques apply equally well to assembly language implementations.

Speech signals are often passed through a pre-emphasis filter to flatten their spectrum prior to additional processing. Pre-emphasis of a signal can be accomplished by applying the following difference equation to the input data:

13

yn + xn * xn*1 ) 32 xn*2

The following implementation is not reentrant because it references and updates the global variables z0 and z1. Even in a non-preemptive environment, this function is not reentrant; it is not possible to use this function to operate on more than one data stream since it retains state for a particular data stream in two fixed variables (z0 and z1).

int z0 = 0, z1 = 0; /* previous input values */

void PRE_filter(int input[], int length)

{

int I, tmp;

for (I = 0; I < length; I++) {

tmp = input[i] - z0 + (13 * z1 + 16) / 32; z1 = z0;

z0 = input[i]; input[i] = tmp;

}

}

We can make this function reentrant by requiring the caller to supply previous values as arguments to the function. This way, PRE_filter1 no longer references any global data and can be used, therefore, on any number of distinct input data streams.

18

General Programming Guidelines

SPRU352G –June 2005 –Revised February 2007

Image 18
Contents Users Guide Rules and GuidelinesSubmit Documentation Feedback Contents Use of the DMA Resource Urls List of Figures Read This First Intended AudienceDocument Overview Rule n Related DocumentationText Conventions Guideline nOverview Scope of the Standard Rules for TMS320C5x Rules for TMS320C6xRules and Guidelines Requirements of the StandardGoals of the Standard Intentional OmissionsSystem Architecture FrameworksAlgorithms Core Run-Time SupportGeneral Programming Guidelines Threads Use of C LanguageThreads and Reentrancy RulePreemptive vs. Non-Preemptive Multitasking ReentrancyExample Data Memory Data MemoryMemory Spaces Scratch versus PersistentScratch vs Persistent Memory Allocation Algorithm versus Application GuidelineProgram Memory ROM-abilitySection Name Purpose Use of Peripherals Use of PeripheralsAlgorithm Component Model Interfaces and Modules Algorithms PackagingInterfaces and Modules Implementation Fir.hExternal Identifiers Naming Conventions Module Initialization and FinalizationModule Instance Objects Design-Time Object Creation Run-Time Object Creation and DeletionModule Configuration Example ModuleMultiple Interface Support Element Interface InheritanceSummary Description RequiredAlgorithms AlgorithmsPackaging Object CodeHeader Files Debug Verses ReleaseModuleversvendorvariant.1arch Algorithm Performance Characterization Data Memory Program Memory Interrupt Latency Execution TimeHeap Memory ExternalSize Stack Memory Static Local and Global Data MemoryData Bss Object files Size Mips Is Not Enough Interrupt LatencyExecution Time OperationExecution Time Model Execution Timeline for Two Periodic TasksProcess 19800059000 198000 Submit Documentation Feedback DSP-Specific Guidelines CPU Register Types Register TypesEndian Byte Ordering Use of Floating PointTMS320C6xxx Rules and Guidelines Data ModelsRegister Use Type Register ConventionsStatus Register CSR Field Use TypeInterrupt Latency TMS320C54xx Rules and GuidelinesProgram Models TMS320C54xx Rules and Guidelines Status Registers ST0 Field Name Use TypeST1 Field Name Use Type TMS320C55x Rules and Guidelines Stack ArchitecturePmst Field Name Use Type Relocatability ExampleSSP Status Bits ST2 Field Name Use TypeST3 Field Name Use Type Homy TMS320C24xx Guidelines GeneralTMS320C28x Rules and Guidelines TMS320C28x Rules and GuidelinesXAR0 M0M1MAP Use of the DMA Resource Submitting DMA Transfer RequestsOverview Algorithm and FrameworkRequirements for the Use of the DMA Resource Logical ChannelData Transfer Properties Data Transfer SynchronizationAbstract Interface DMA GuidelineDMA Rule Resource Characterization Data Transfers bytes FrequencyAverage Maximum Runtime APIs Strong Ordering of DMA Transfer RequestsSubmitting DMA Transfer Requests Device Independent DMA Optimization GuidelineCache Coherency Issues for Algorithm Producers 13 C6xxx Specific DMA Rules and GuidelinesSupporting Packed/Burst Mode DMA Transfers 14 C55x Specific DMA Rules and GuidelinesInter-Algorithm Synchronization Minimizing Logical Channel Reconfiguration OverheadAddressing Automatic Endianism Conversion Issues Non-Preemptive SystemPreemptive System Algorithm B Algorithm a Inter-Algorithm Synchronization Appendix a General Rules Performance Characterization Rules DMA RulesGeneral Guidelines DMA Guidelines Submit Documentation Feedback DSP/BIOS Run-time Support Library Core Run-Time APIsDSP/BIOS Run-time Support Library TI C-Language Run-Time Support LibraryBibliography BooksSubmit Documentation Feedback Glossary Glossary of TermsGlossary of Terms Glossary of Terms Important Notice