BR: Thread::sleep does not sleep for the requested time

Create a standard JUCE GUI app, in the constructor for the Component add the following code:

	DBG(juce::Time::getCurrentTime().toString(false, true));
	juce::Thread::sleep (10 * 1000);
	DBG(juce::Time::getCurrentTime().toString(false, true));

You would expect it to sleep for 10 seconds, but the output is:

JUCE v8.0.6
4:42:17pm
4:42:17pm

The correct implementation of sleep is:

void JUCE_CALLTYPE Thread::sleep (int millisecs)
{
	while (millisecs > 0)
	{
		struct timespec time;
		time.tv_sec = millisecs / 1000;
		time.tv_nsec = (millisecs % 1000) * 1000000;

		struct timespec remaining;

		if (nanosleep (&time, &remaining) == -1)
			millisecs = int (remaining.tv_sec * 1000 + time.tv_nsec / 1000000);
		else
			return;
	}
}

then the output is:

JUCE v8.0.6
4:43:21pm
4:43:31pm

Reproduced on macOS 15.1.1

1 Like

Thank you for submitting, this looks like a reasonable suggestion. I’ll update the thread when this is merged.

1 Like

It’s probably actually cleaner to write it like this, but doesn’t make a big difference.

void JUCE_CALLTYPE Thread::sleep (int millisecs)
{
    struct timespec time;
    time.tv_sec = millisecs / 1000;
    time.tv_nsec = (millisecs % 1000) * 1000000;

    struct timespec remaining;

    while (nanosleep (&time, &remaining) == -1)
        time = remaining;
}
1 Like

Or

std::this_thread::sleep_for (std::chrono::milliseconds (millisecs));

?

7 Likes

A fix is now out on develop

1 Like