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;
}

1 Answer 1

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.

6
  • 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 7, 2021 at 6:39
  • Is there anything to yield to in the AVR core?
    – AndreKR
    Nov 7, 2021 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 7, 2021 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 9, 2021 at 8:56
  • 1
    Not "lower than" but "not greater than". Subtle difference.
    – Majenko
    Nov 9, 2021 at 9:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.