"delay(2)" in loop to "allow cpu to switch"?

At the end of this esp32 arduino core demo code, there is a short loop() method, and at the end of it the last line of code is:

delay(2);//allow the cpu to switch to other tasks

...everything I read online suggests that there is no point in a delay like this. Is this something that might make sense on some MCU architectures but not others? Or is there something nuanced about this code that makes a delay like that useful?

This is necessary for "cooperative" multi-tasking, which is much less demanding than "pre-emptive" mulltitasking where another core spends it's time watching and interrupting one task to allow another task some cpu cycles.

Thanks Paul -- I'm trying to read up on this per your reply -- the linked code isn't doing any multitasking itself, is it? Isn't delay() just a busy wait anyway, which would prevent task switching as effectively as any regular code?

I guess I'm just confused why this shows up in this example code and no other demo code I've seen. The implication is that a regular loop() is going to starve some background tasks or something, but my impression was that in this context that wasn't a concern...

On an ESP, there is NO reason to include that delay. Simply returning from loop() will give any other "ready" tasks their CPU time.

And delay() is NOT a "busy wait". It will sleep the loop() task, and allow other tasks to run, exactly as returning from loop() will do.

Oh yeah, look at that:

void delay(uint32_t ms)
{
    vTaskDelay(ms / portTICK_PERIOD_MS);
}

So the reason the delay(2) is in that demo code is because on some processor architectures it is required? That demo is in the ESP32 Arduino Core codebase, so I would expect it to be needed on an ESP32 of some kind? Or is it simply copy/paste code and should be ignored?

Related question: in a stock ESP32 loop() running a simple LED blinker demo, are there in fact any "background tasks" of any kind going on? I.e. if I do a "while(1);" in my loop() is it going to starve all ISRs or timers or something?

I suggest you try it and see for yourself...

In practice you do appear to need a small delay in an otherwise empty loop(). I did a simple RTOS esp32 simulation of a traffic light problem and discovered that if the loop was empty, it did not perform correctly in that in the simulator it performed at only a fraction of real time. With a delay it was OK. traffic light RTOS - Wokwi ESP32, STM32, Arduino Simulator

Interesting, thanks for that.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.