c++ sleep
#include <iostream>
#include <chrono>
#include <thread>
int main() {
// Sleep for 2 seconds
std::chrono::seconds duration(2);
std::this_thread::sleep_for(duration);
// Code resumes after 2 seconds
std::cout << "Slept for 2 seconds!" << std::endl;
return 0;
}
This C++ code snippet demonstrates the usage of the sleep_for
function from the <thread>
header. It includes the necessary headers (iostream
, chrono
, and thread
). Inside the main
function, it creates a std::chrono::seconds
object named duration
initialized to 2 seconds. The sleep_for
function pauses the execution of the program for the specified duration. After waiting for 2 seconds, the program prints "Slept for 2 seconds!" to the console using std::cout
. Finally, the program returns 0, indicating successful execution.