Search code examples
c++cross-platformwait

Is there a wait function in C++?


I have been working on a program, and it makes use of the sleep() function. I want it to be cross platform for macOS, Linux, and Windows but having three branches is tedious to work with and is terrible to do. What can I do to make it cross platform? And what functions that make the program wait for a few seconds work? When I test it, it doesn’t even work...

Linux code doesn’t seem to work...

#include <iostream>
#include <unistd.h>

using namespace std;


int loading() {
  sleep(0.25);
  cout << "Loading... ";
  sleep(0.25);
  cout << "hi";
  sleep(0.25);
  cout << "e";
  sleep(0.25);
  return 0;
}
int main() {
  loading();
  return 0;
}

Neither does Windows...

#include <iostream>
#include <windows.h>

using namespace std;


int loading() {
  Sleep(250);
  cout << "Loading... ";
  Sleep(250);
  cout << "hi";
  Sleep(250);
  cout << "e";
  Sleep(250);
  return 0;
}
int main() {
  loading();
  return 0;
}

Is the syntax wrong, or am I using it incorrectly?


Solution

  • Since C++11, you might use std::this_thread::sleep_for

    using namespace std::chrono_literals;
    
    std::this_thread::sleep_for(250ms);