Developers Notes
  • Welcome
  • Developer
    • Java
      • JUnit
        • Parameterized Test
        • Introduction to WireMock
      • Maven
        • Resource Reader and Writer
        • JUnit with Maven
        • Maven Run
        • A Quick Guide to Maven Wrapper
      • Spring
        • Autowired vs Resource
        • Spring OpenFeign 사용시 https 신뢰하는 방법
        • Aspect with Annotation
        • Spring JPA에서 Tibero를 사용하기 위한 설정
        • Spring module dependency
        • Mockito
          • Autowired @Value field in Spring with Mockito
        • SpringBoot Hybernate application.yml
        • ReflectionTestUtils
        • Spring Properties File Outside jar
        • Spring @RequestParam Annotation
        • Properties with Spring and Spring Boot
        • Passing JVM Options from Gradle bootRun
        • Securing Spring Boot API With API Key and Secret
        • Why Is Field Injection Not Recommended?
        • An Overview of Identifiers in Hibernate/JPA
      • Etcs
        • BigDecimal 사용시 주의 사항
        • static factory methods common naming conventions
        • List of Lists into a List (Stream)
        • Return null in stream
        • Logging with Lombok
        • JPA
        • Big-O Java Collections
    • MySQL
      • Active Connections on MySQL
      • MariaDB-Galera
      • FOUND_ROWS
      • MySQL Group Replication Requirements
      • Data Types Explicit Default Handling
    • C/C++
      • Autotool 사용법
      • Intruduction to GNU Autotools
      • mysql
        • C Api Flow
        • MySQL Connector/C++ 8.3 Developer Guide
      • Common vulnerabilities guide for C programmers
      • HTTP in C++
      • JSON in C++
      • How to get memory usage at runtime using C++?
      • How to get time in milliseconds using C++ on Linux?
      • Sleep Functions in C++
      • Calculate Cpu Usage on Linux as Top
    • CryptoGraphy
      • 인증 기관(CA;Certificate Authority) 구성하고 인증서 발급하기
      • KeyTool Import PrivateKey, Certificate
      • Java Keytool 사용법
      • PKCS, Public Key Cryptography Standard
      • CER/DER/CRT/CSR 형식 파일이란?
      • FIPS 140-2
      • SSL 인증서 발급
      • 사용법, tip 정리
      • OpenSSL
        • OpenSSL guide
        • Openssl RSA Private Key Encrypt
      • How to Read PEM File to Get Public and Private Keys
    • PKCS#11 API
      • PKCS#11 API-강좌1
      • PKCS#11 API-강좌2
      • PKCS#11 API-강좌3
      • PKCS#11 API-강좌4
      • PKCS#11 API-강좌5(C 언어로 된 Sample Code)
      • PKCS#11 API-강좌6(EC Key 생성 및 Signing)
    • Warehouse of PKI
    • GoLang
      • go-cshared-examples
      • Fun building shared libraries in Go
      • Golang time
      • Encoding Json
  • OpenSSL
    • OpenSSL Document
      • openssl-req
      • x509v3_config
      • Openssl Example
    • Creating a Self-Signed Certificate With OpenSSL
    • Openssl 3.x Provider
      • Writing OpenSSL Provider Skeleton
    • OpenSSL Certificate Command
  • DevOps
    • Docker
      • Environment Variables for MariaDB or MySQL Docker
      • Container Technology, Docker
      • Docker Trouble Shooting
      • Docker BuildKit
      • How to clear Docker cache and free up space on your system
    • Cloud
      • Serverless Architecture
      • AWS
        • AWS 주요 자습서 Link
        • Diagram-as-code for AWS architecture.
        • AWS Architecture icon
      • Install MariaDB Galera by Helm
      • Jenkinsfile VIM syntax highlighting
      • Cloud Development Kit for Kubernetes
    • VM
      • vagrant를 사용한 vm 설치 방법
    • Etcs
      • Logstash
        • Installing Logstash
        • Configuration Logstash Output
      • Rancher Install
      • Install ELK
      • Simpler Tool for Deploying Rancher
    • Ubuntu
      • Install SFTP Client
  • Etcs
    • Etcs
      • Useful Tools
      • Links
      • Entertainment
Powered by GitBook
On this page
  • Sleep
  • Similar Functions Like sleep in C++
  • 1. usleep():
  • 2. sleep_for():
  • 3. sleep_until():
Edit on GitHub
  1. Developer
  2. C/C++

Sleep Functions in C++

C++ provides the functionality of delay or inactive state with the help of the operating system for a specific period of time. Other CPU operations will function adequately but the Sleep() function in C++ will sleep the present executable for the specified time by the thread. It can be implemented using 2 libraries according to the operating system being used:

#include<windows.h>           // for windows

#include<unistd.h>               // for linux 

Sleep

Sleep can suspend execution for time_period where time_period is in seconds by default although we can change it to microseconds.

Syntax:

sleep( time_period );    // time_period in seconds

Parameter: time_period is in seconds it represents the sleep time taken.

Return Type: The return type of sleep function is an integer where if the function is successfully executed then the value returned will be 0, else minus the value of the time period returned.

Example:

// C++ Program to show how to use
// sleep function
#include <iostream>

// Library effective with Windows
#include <windows.h>

// Library effective with Linux
#include <unistd.h>

using namespace std;

// Driver code
int main()
{
    cout << "Join the Line:\n";
    cout << "Wait for 5 seconds\n";

    // sleep will schedule rest of 
    // activities after 10 seconds
    sleep(5);

    cout << "It's your time buy ticket";
}

Output:

Similar Functions Like sleep in C++

1. usleep():

This function is mostly similar to sleep but can only be used with <unistd.h> library.

Syntax:

usleep(time_period)   // time_period in microseconds

Parameter: It takes time_period where time_period is by default in microseconds. 1 second = 10^6 microseconds.

Return Type: Integer where it returns 0 if successful, and (-1 or -exp) if the process failed.

Example:

// C++ Program to show the 
// use of usleep function
#include <iostream>
#include <unistd.h>

using namespace std;

int main()
{
	cout << "Take your Position\n";

	// sleep for 10 seconds
	cout << "Wait for 5 seconds\n";
	usleep(5000000);

	cout << "Run! Run!";
	return 0;
}

Output:

2. sleep_for():

Schedules thread for the specified time. It acts like a delay just like sleep function. However, It is possible that threads take more time than the scheduled time due to scheduling activities or can be resource contention delays. Library used <thread>.

Syntax:

this_<thread_name>::sleep_for(chorno:: time_duration (time_period))         

Parameter: time_period ( time for which thread is acquired )

Example:

// C++ Program to demonstrate 
// sleep_for()function
#include <iostream>
#include <chrono>
#include <thread>
using namespace std;

// Driver cpde
int main()
{
    cout << "Thread is running\n";

    // Thread delayed for 5 seconds
    this_thread::sleep_for(chrono::milliseconds(5000));

    cout << "Thread was acquired for 5 seconds\n";

    return 0;
}

Output:

3. sleep_until():

Blocks the execution of a thread until the sleep_time is finished. However, even when sleep_time has been reached due to scheduling or resource contention delays it could take more time than sleep_time. Library used <thread>.

Syntax:

this_<thread_name>::sleep_until(awake_time) 

Parameter: Sleep_time (same time for which thread is blocked for execution)

Example:

// C++ Program to demonstrate
// sleep_until()
#include <chrono>
#include <iostream>
#include <thread>

// Functioning returning 
// current time
auto now() 
{
	return std::chrono::steady_clock::now(); 
}

// Function calculating sleep time 
// with 2000ms delay
auto awake_time()
{
	using std::chrono::operator"" ms;
	return now() + 2000ms;
}

// Driver code
int main()
{
	std::cout << "Starting the operation .....\n" << std::flush;

	// Calculating current time
	const auto start{ now() };

	// using the sleep_time to delay
	// and calculating sleep time
	// using awake_time function
	std::this_thread::sleep_until(awake_time());

	// storing time for printing
	std::chrono::duration<double, std::milli> elapsed{
		now() - start
	};

	// printing waiting time
	std::cout << "Waited for : " << elapsed.count() << " ms\n";
}

Output:

PreviousHow to get time in milliseconds using C++ on Linux?NextCalculate Cpu Usage on Linux as Top

Last updated 1 year ago

Sleep Function in C++ - GeeksforGeeksGeeksforGeeks
Logo