24
CHAPTER 4
Thread-Local Storage TLS
4.3 Thread-Local Storage TLS
The DLib of Cortex-M supports usage of thread-local storage. Several library objects and
functions need local variables which have to be unique to a thread. Thread-local storage
will be required when these functions are called from multiple threads.
embOS for Cortex-M is prepared to support the tread-local storage, but does not use it per
default. This has the advantage of no additional overhead as long as thread-local storage is
not needed by the application. The embOS implementation of thread-local storage allows
activation of TLS separately for every task.
Only tasks that call functions using TLS need to activate the TLS by calling an initialization
function when the task is started.
The IAR runtime environment allocates the TLS memory on the heap. Using TLS with multi-
ple tasks shall therefore use thread-safe system library functionality which is automatically
enabled when the
xmtx.c
module from the embOS distribution is added to the project.
Library objects that need thread-local storage when used in multiple tasks are:
• error functions -- errno, strerror.
• locale functions -- localeconv, setlocale.
• time functions -- asctime, localtime, gmtime, mktime.
• multibyte functions -- mbrlen, mbrtowc, mbsrtowc, mbtowc, wcrtomb, wcsrtomb,
wctomb.
• rand functions -- rand, srand.
• etc functions -- atexit, strtok.
• C++ exception engine.
4.3.1 OS_TASK_SetContextExtensionTLS()
Description
OS_TASK_SetContextExtensionTLS()
may be called from a task to initialize and use
thread-local storage.
This API is not available in embOS library mode
OS_LIBMODE_SAFE
.
Prototype
void
OS_TASK_SetContextExtensionTLS(
void
);
Additional information
OS_TASK_SetContextExtensionTLS()
shall be the first function called from a task when
TLS should be used in the specific task. The function must not be called multiple times
from one task. The thread-local storage is allocated on the heap. To ensure thread-safe
heap management, the thread-safe system library functionality shall also be enabled when
using TLS.
Thread-safe system library calls are automatically enabled when the source module
xmtx.c
which is delivered with embOS in the BSP Setup folders is included in the project.
Example
The following printout demonstrates the usage of task specific TLS in an application.
#include
"RTOS.h"
static
OS_STACKPTR
int
StackHP[
128
], StackLP[
128
];
// Task stacks
static
OS_TASK TCBHP, TCBLP;
// Task control blocks
static
void
HPTask(
void
) {
OS_TASK_SetContextExtensionTLS();
while
(
1
) {
errno =
42
;
// errno specific to HPTask
embOS-MPU for Cortex-M and IAR
© 2010-2020 SEGGER Microcontroller GmbH