Surfer on the fall
Surfer on the fall

Reputation: 733

c++11: how to execute a function in the main thread after n seconds

I need to stop a game after a certain amount of time. The stop method has to run in the main thread after, let's say, one minute. In the meantime the player plays, so I cannot stop execution. I'm trying to understand threads and async but I'm starting to think that none of them are useful in my situation (if I join, the user can't play; if I detach, the 'stop' method will be called in a separate thread). How could I deal with it? Thanks a lot

Upvotes: 1

Views: 942

Answers (3)

AndersK
AndersK

Reputation: 36082

Just start your stop function with std::async, then inside of your stop function have a std::this_thread.sleep_for(60s) as a first call

e.g.

#include <future>
...
std::future<int> retCode = std::async(stop);
.. your game starts

inside of int stop()

int stop()
{
  std::this_thread::sleep_for(std::chrono::minute(1));
  ...do whatever to stop game...
}

Upvotes: 1

marc h&#252;skens
marc h&#252;skens

Reputation: 13

If you really need/want to use Threads, You should have a look at the QtConcurrent Framework. The QRunnable QThreadPool is really easy to use.

http://doc.qt.io/qt-5/qtconcurrent-index.html

Upvotes: 0

Some programmer dude
Some programmer dude

Reputation: 409136

In the "main thread" you are supposedly having an event loop, yes? Before the loop start, get the current time, and then in the loop get the current time again and check the difference between the first time and the current time in the loop.

Upvotes: 0

Related Questions