Thread/interrupt-safeness of esp_timer_get_time
Posted: Thu Sep 07, 2023 11:18 am
Dear all,
currently I implement software for ESP32 which frequently calls `int64_t current_time = esp_timer_get_time()`. Each time I check if `current_time - last_updated > INTERVAL`, where `last_updated` is a 64 bit signed integer. Since the ESP32 is a 32 bit processor, there are no 64 bit atomics, thus the compiler generates code which uses at least two instructions for reading esp_timer_get_time() into the variable `current_time` or into whatever memory area the compiler decides -- those instructions potentially could be interrupted by a timer interrupt. This leads to undefined behavior and thus is highly dangerous for my software, which relies on correct timing. Even though this is highly unlikely to happen, the chance is still not zero. I cannot take this risk.
How do I avoid such? One classic approach would be to use a mutex or similar locking mechanism, but I don't have access to the timer interrupt incrementing the underlying timer variable, so I can't prepend a lock and append an unlock.
Do you have any idea to make esp_timer_get_time() thread-safe?
Best, chris
currently I implement software for ESP32 which frequently calls `int64_t current_time = esp_timer_get_time()`. Each time I check if `current_time - last_updated > INTERVAL`, where `last_updated` is a 64 bit signed integer. Since the ESP32 is a 32 bit processor, there are no 64 bit atomics, thus the compiler generates code which uses at least two instructions for reading esp_timer_get_time() into the variable `current_time` or into whatever memory area the compiler decides -- those instructions potentially could be interrupted by a timer interrupt. This leads to undefined behavior and thus is highly dangerous for my software, which relies on correct timing. Even though this is highly unlikely to happen, the chance is still not zero. I cannot take this risk.
How do I avoid such? One classic approach would be to use a mutex or similar locking mechanism, but I don't have access to the timer interrupt incrementing the underlying timer variable, so I can't prepend a lock and append an unlock.
Do you have any idea to make esp_timer_get_time() thread-safe?
Best, chris