execute function in C++ after a delay without using sleep

psychojim picture psychojim · Nov 6, 2014 · Viewed 9.8k times · Source

is there a simple way of making something happen after a specific delay in C++? In python, I just use frame.after(ms,myFunction) which is nice and easy - it seems like a far trickier problem in C++! It has previously been suggested that I use Sleep(), unfortunately this doesn't work as I am writing a mod for Half-Life 2 and if I use Sleep then the whole game hangs for X seconds rather than just calling the event after X seconds. So is there another way to call a function after a specific delay without using sleep?

Answer

deW1 picture deW1 · Nov 6, 2014

Basically you have 2 options imho:

  1. Create a second thread which will sleep instead of your main thread.
  2. Create a second thread which contains a timer.

I can only recommend boosts io_service

You might want to go through all the timer tutorials if you're new to boost.


If you want to stay with the std check this link for more information on std::async

And this for a guide on how to use std::threads