123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117 |
- #ifndef SINGLETONPTR_H
- #define SINGLETONPTR_H
- #include <stdint.h>
- #include <new>
- #include "platform/mbed_assert.h"
- #ifdef MBED_CONF_RTOS_PRESENT
- #include "cmsis_os2.h"
- #endif
- #ifdef MBED_CONF_RTOS_PRESENT
- extern osMutexId_t singleton_mutex_id;
- #endif
- inline static void singleton_lock(void)
- {
- #ifdef MBED_CONF_RTOS_PRESENT
- osMutexAcquire(singleton_mutex_id, osWaitForever);
- #endif
- }
- inline static void singleton_unlock(void)
- {
- #ifdef MBED_CONF_RTOS_PRESENT
- osMutexRelease(singleton_mutex_id);
- #endif
- }
- template <class T>
- struct SingletonPtr {
-
- T *get()
- {
- if (NULL == _ptr) {
- singleton_lock();
- if (NULL == _ptr) {
- _ptr = new (_data) T();
- }
- singleton_unlock();
- }
-
-
- MBED_ASSERT(_ptr == (T *)&_data);
- return _ptr;
- }
-
- T *operator->()
- {
- return get();
- }
-
- T *_ptr;
-
- uint32_t _data[(sizeof(T) + sizeof(uint32_t) - 1) / sizeof(uint32_t)];
- };
- #endif
|