Modifying the system time to the past, sleep_for will cause the program to get stuck.

RL Chen 250 Reputation points
2023-09-22T08:34:32.6+00:00

When the program runs to std::this_thread::sleep_for(std::chrono::milliseconds(1));, if the system time is switched back at this moment, the program will freeze.” I want to know how to avoid this situation.

The following code is for you to test, after you start running it switch the system time to the past and you will see that the program is stuck. Environment: MSVC v143 C++17.

#include <iostream> 
#include <thread> 
using namespace std;  
int main() 
{ 	
	for (int i = 1; i; i++) 	
	{ 		
		cout << i << endl; 		
		std::this_thread::sleep_for(std::chrono::milliseconds(1)); 	
	}  	
	return 0; 
}

I need a viable solution or alternative, please.

C++
C++
A high-level, general-purpose programming language, created as an extension of the C programming language, that has object-oriented, generic, and functional features in addition to facilities for low-level memory manipulation.
3,834 questions
{count} votes

Accepted answer
  1. Minxin Yu 12,506 Reputation points Microsoft Vendor
    2023-09-26T06:45:45.6733333+00:00

    Hi, @RL Chen

    I reproduced the problem:

    Start the program, set the time back 5mins, and then set it to the current time. I still need to wait 5 minutes before the program continues.

    For 2 days is set, the program will wait 2 days.

    As David said, MSVC seems to use system clock.

    You can submit reports on the Developer Community.

    Window API is an alternative:

    #include<Windows.h>
    Such as

    Sleep function is not affected by changing the system clock.

    Best regards,

    Minxin Yu


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


1 additional answer

Sort by: Most helpful
  1. Deleted

    This answer has been deleted due to a violation of our Code of Conduct. The answer was manually reported or identified through automated detection before action was taken. Please refer to our Code of Conduct for more information.


    Comments have been turned off. Learn more

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.