5

I've seen some code where the developers add delay(0), it doesnt make sense, what does it do? Delay with zero milliseconds, why?

bool DFRobotDFPlayerMini::waitAvailable(unsigned long duration){
  unsigned long timer = millis();
  if (!duration) {
    duration = _timeOutDuration;
  }
  while (!available()){
    if (millis() - timer > duration) {
      return false;
    }
    delay(0);
  }
  return true;
}
Sigma
  • 296
  • 3
  • 13

1 Answers1

9

Delay (traditionally) has two functions that it performs:

  1. Wait for a period
  2. Yield processing to other threads through the yield() weak symbol.

By using a delay(0) the author thinks they are saying "I don't want to delay here, but if anything is using the yield() function it can run now."

However, that is not correct.

The code for delay() in the AVR core looks like this:

void delay(unsigned long ms) 
{
    uint32_t start = micros();

    while (ms > 0) {
        yield();
        while ( ms > 0 && (micros() - start) >= 1000) {
            ms--;
            start += 1000;
        }
    }   
}

You can see that, as well as delaying for a period, yield() is regularly called. However that only ever happens if ms is greater than 0. If you pass 0 as the delay length then the delay() function essentially does nothing at all.

Now it could be that an earlier version of the core had yield() always being called even with ms==0, but the current version doesn't. Maybe this is a hangup from an old coding style. But for the current core if you want to yield you must explicitly call yield() or delay for at least one millisecond.

ocrdu
  • 1,673
  • 2
  • 9
  • 22
Majenko
  • 103,876
  • 5
  • 75
  • 133
  • 2
    esp8266 `delay` has yield with 0 delay and esp32 `delay` directly calls vTaskDelay in SDK. The mded cores call RTOS thread sleep. – Juraj Nov 07 '21 at 06:39
  • Is there anything to yield *to* in the AVR core? – AndreKR Nov 07 '21 at 23:29
  • @AndreKR Not in the core, no. `yield()` is defined "weak" so that you (or a library) can override it to implement a form of crude cooperative threading. – Majenko Nov 07 '21 at 23:30
  • Yepp this is exactly what i saw when looking at the delay() method. That made it more confusing. So it does nothing since milliseconds is lower then zero. – Sigma Nov 09 '21 at 08:56
  • 1
    Not "lower than" but "not greater than". Subtle difference. – Majenko Nov 09 '21 at 09:50
  • @Majenko Sorry =P – Sigma Nov 10 '21 at 20:17