Use of sleep functions instead of wait

What is better for use in a library, which should also backward compatible to mbed 5?

  • ThisThread::sleep_for()
  • thread_sleep_for()

e.g. ThisThread::sleep_for(100us) is not workin only ms or s works
so I have to use wait_us() instead?
How to use the chrono literals with variables? I want use ThisThread::sleep_for() with a variable as an argument, but a number without a literal is deprecated.

I think does not matter which function is good or bad. Importance is matter if you are at place where response in some micro_second require. From memory point of view you should try to do same program using both functions and check binary image size.

Doesn’t matter how you use all these functions (delay related) ,This is because you are end with pause the task for some times.
ThisThread::sleep_for() or wait() both are using internal timer of micro and providing same result almost.

Basically , sleep /or wait function is useful if you are using RTOS , where scheduler switch another thread /or process because you are not doing any importance task in current thread. Many times developer use this to context switch another thread (some thing like yield() function).

This is a time where micro running on more than 80 MHz clock speed with multistage pipeline concepts, not like Arduino (8 MHz) . So you can do multiple things in parallel but your single core CPU ideally run one instruction at a time. So sometime you need to provide time slot for other processes (specially when high priority task is in running state ,and low priority task waiting for its turn) at that time these type of sleep for some ms helps to turn on another thread and back to main thread.

Hello Stefan,

You can have for example:

    int delay = 500;
        
#if MBED_MAJOR_VERSION == 2
    wait_ms(delay);
#elif MBED_MAJOR_VERSION == 5
    thread_sleep_for(delay);
#else
    ThisThread::sleep_for(chrono::milliseconds(delay));
#endif

Best regards, Zoltan

3 Likes

Thank you, that’s what I’m missed.