Hi,
Multitasking is new to me, as is the ESP32 and ESP IDF framework.
I'm using a float variable, to share a value between tasks. Were it a 32-bit variable, I believe it's writes would be atomic. As a float value, however, I'm concerned that the reading task may acquiring the value, right in the middle of a non atomic series of write operations in the writing task, and hence read erroneous data.
Global floats probably aren't the best way to share values between tasks, but in a pinch, what's the most efficient means to enforce atomicity when the writing task adds new data? Critical section?
G.
Make global float atomic?
-
- Posts: 9766
- Joined: Thu Nov 26, 2015 4:08 am
Re: Make global float atomic?
A float is a 32-bit value, so I'd say that it should be atomic by default, but I don't know for sure. In case it's not, to make anything 'atomic', you could put a spinlock or a mutex around it.
-
- Posts: 1735
- Joined: Mon Oct 17, 2022 7:38 pm
- Location: Europe, Germany
Re: Make global float atomic?
On the ESPs, float is 'single precision", i.e. 32-bit. You can verify that by checking sizeof(float).
As you noted, this means that a float will be atomically read/written to RAM (unless it's a member of a 'packed' struct).
In other cases, using the spinlock mutex via taskENTER_CRITICAL()/taskEXIT_CRITICAL() would be the fastest way to ensure mutual exclusion.
If you want to be more platform-independent and/or want more control over memory access ordering, you can alternatively use C++'s std::atomic or C's _Atomic.
As you noted, this means that a float will be atomically read/written to RAM (unless it's a member of a 'packed' struct).
In other cases, using the spinlock mutex via taskENTER_CRITICAL()/taskEXIT_CRITICAL() would be the fastest way to ensure mutual exclusion.
If you want to be more platform-independent and/or want more control over memory access ordering, you can alternatively use C++'s std::atomic or C's _Atomic.
Re: Make global float atomic?
Awesome!
Thank you both ESP_Sprite and MicroController.
That's answered my query nicely.
G.
Thank you both ESP_Sprite and MicroController.
That's answered my query nicely.
G.
Who is online
Users browsing this forum: jjsch-dev and 103 guests