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
  • 4
  • 13

1 Answers1

10

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,795
  • 3
  • 12
  • 24
Majenko
  • 105,851
  • 5
  • 82
  • 139