Make global float atomic?

GreenBEM
Posts: 5
Joined: Mon Nov 13, 2023 12:41 pm

Make global float atomic?

Postby GreenBEM » Thu Jan 18, 2024 11:21 pm

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:

ESP_Sprite
Posts: 9766
Joined: Thu Nov 26, 2015 4:08 am

Re: Make global float atomic?

Postby ESP_Sprite » Fri Jan 19, 2024 2:01 am

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.

MicroController
Posts: 1735
Joined: Mon Oct 17, 2022 7:38 pm
Location: Europe, Germany

Re: Make global float atomic?

Postby MicroController » Fri Jan 19, 2024 10:46 am

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.

GreenBEM
Posts: 5
Joined: Mon Nov 13, 2023 12:41 pm

Re: Make global float atomic?

Postby GreenBEM » Sat Jan 20, 2024 10:59 pm

Awesome!

Thank you both ESP_Sprite and MicroController.

That's answered my query nicely.

G.

Who is online

Users browsing this forum: Vitalii_Bondarenko and 125 guests