168
168
#include "cmsis_os2.h"
169
169
#include "mbed_toolchain.h"
170
170
#include "mbed_error.h"
171
+ #include "mbed_critical.h"
171
172
#if defined(__IAR_SYSTEMS_ICC__ ) && (__VER__ >= 8000000 )
172
173
#include <DLib_Threads.h>
173
174
#endif
@@ -423,6 +424,7 @@ void __rt_entry (void) {
423
424
}
424
425
425
426
typedef void * mutex ;
427
+ mutex _static_mutexes [OS_MUTEX_NUM ] = {NULL };
426
428
427
429
/* ARM toolchain requires dynamically created mutexes to enforce thread safety. There's
428
430
up to 8 static mutexes, protecting atexit, signalinit, stdin, stdout, stderr, stream_list,
@@ -441,9 +443,23 @@ int _mutex_initialize(mutex *m)
441
443
attr .name = "ARM toolchain mutex" ;
442
444
attr .attr_bits = osMutexRecursive | osMutexPrioInherit | osMutexRobust ;
443
445
444
- * m = osMutexNew (& attr );
445
- if (* m != NULL ) {
446
- return 1 ;
446
+ mutex * slot = NULL ;
447
+ core_util_critical_section_enter ();
448
+ for (int i = 0 ; i < OS_MUTEX_NUM ; i ++ ) {
449
+ if (_static_mutexes [i ] == NULL ) {
450
+ _static_mutexes [i ] = (mutex )- 1 ; // dummy value to reserve slot
451
+ slot = & _static_mutexes [i ];
452
+ break ;
453
+ }
454
+ }
455
+ core_util_critical_section_exit ();
456
+
457
+ if (slot != NULL ) {
458
+ * m = osMutexNew (& attr );
459
+ * slot = * m ;
460
+ if (* m != NULL ) {
461
+ return 1 ;
462
+ }
447
463
}
448
464
449
465
/* Mutex pool exhausted, try using HEAP */
@@ -463,6 +479,28 @@ int _mutex_initialize(mutex *m)
463
479
return 1 ;
464
480
}
465
481
482
+ void _mutex_free (mutex * m ) {
483
+ mutex * slot = NULL ;
484
+ core_util_critical_section_enter ();
485
+ for (int i = 0 ; i < OS_MUTEX_NUM ; i ++ ) {
486
+ if (_static_mutexes [i ] == * m ) {
487
+ slot = & _static_mutexes [i ];
488
+ break ;
489
+ }
490
+ }
491
+ core_util_critical_section_exit ();
492
+
493
+ osMutexDelete (* m );
494
+
495
+ // if no slot reserved for mutex, must have been dynamically allocated
496
+ if (!slot ) {
497
+ free (m );
498
+ } else {
499
+ * slot = NULL ;
500
+ }
501
+
502
+ }
503
+
466
504
#endif /* ARMC */
467
505
#elif defined (__GNUC__ ) /******************** GCC ********************/
468
506
0 commit comments