Skip to content

Commit 793f9c5

Browse files
committed
Add partial thread safety to GCC
Add lock functions so that malloc and environment variable access are thread safe. Add the compiler option "-o thread-safe" to use the full version of newlib which is thread safe. Note that this patch does NOT make file access thread safe.
1 parent bd216c3 commit 793f9c5

File tree

2 files changed

+32
-1
lines changed

2 files changed

+32
-1
lines changed

rtos/rtx/TARGET_CORTEX_M/RTX_CM_lib.h

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -624,11 +624,18 @@ __asm void __rt_entry (void) {
624624

625625
#elif defined (__GNUC__)
626626

627+
osMutexDef(malloc_mutex);
628+
static osMutexId malloc_mutex_id;
629+
osMutexDef(env_mutex);
630+
static osMutexId env_mutex_id;
631+
627632
extern void __libc_fini_array(void);
628633
extern void __libc_init_array (void);
629634
extern int main(int argc, char **argv);
630635

631636
void pre_main(void) {
637+
malloc_mutex_id = osMutexCreate(osMutex(malloc_mutex));
638+
env_mutex_id = osMutexCreate(osMutex(env_mutex));
632639
atexit(__libc_fini_array);
633640
__libc_init_array();
634641
main(0, NULL);
@@ -651,6 +658,29 @@ __attribute__((naked)) void software_init_hook (void) {
651658
);
652659
}
653660

661+
// Opaque declaration of _reent structure
662+
struct _reent;
663+
664+
void __malloc_lock( struct _reent *_r )
665+
{
666+
osMutexWait(malloc_mutex_id, osWaitForever);
667+
}
668+
669+
void __malloc_unlock( struct _reent *_r )
670+
{
671+
osMutexRelease(malloc_mutex_id);
672+
}
673+
674+
void __env_lock( struct _reent *_r )
675+
{
676+
osMutexWait(env_mutex_id, osWaitForever);
677+
}
678+
679+
void __env_unlock( struct _reent *_r )
680+
{
681+
osMutexRelease(env_mutex_id);
682+
}
683+
654684
#elif defined (__ICCARM__)
655685

656686
extern void* __vector_table;

workspace_tools/toolchains/gcc.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -183,7 +183,8 @@ def __init__(self, target, options=None, notify=None, macros=None, silent=False,
183183
GCC.__init__(self, target, options, notify, macros, silent, GCC_ARM_PATH, extra_verbose=extra_verbose)
184184

185185
# Use latest gcc nanolib
186-
self.ld.append("--specs=nano.specs")
186+
if "thread-safe" not in self.options:
187+
self.ld.append("--specs=nano.specs")
187188
if target.name in ["LPC1768", "LPC4088", "LPC4088_DM", "LPC4330", "UBLOX_C027", "LPC2368"]:
188189
self.ld.extend(["-u _printf_float", "-u _scanf_float"])
189190
elif target.name in ["RZ_A1H", "VK_RZ_A1H", "ARCH_MAX", "DISCO_F407VG", "DISCO_F429ZI", "DISCO_F469NI", "NUCLEO_F401RE", "NUCLEO_F410RB", "NUCLEO_F411RE", "NUCLEO_F446RE", "ELMO_F411RE", "MTS_MDOT_F411RE", "MTS_DRAGONFLY_F411RE", "DISCO_F746NG"]:

0 commit comments

Comments
 (0)