Page 1 of 1

Make global float atomic?

Posted: Thu Jan 18, 2024 11:21 pm
by GreenBEM
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. :shock:

Re: Make global float atomic?

Posted: Fri Jan 19, 2024 2:01 am
by ESP_Sprite
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.

Re: Make global float atomic?

Posted: Fri Jan 19, 2024 10:46 am
by MicroController
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.

Re: Make global float atomic?

Posted: Sat Jan 20, 2024 10:59 pm
by GreenBEM
Awesome!

Thank you both ESP_Sprite and MicroController.

That's answered my query nicely.

G.