Reputation: 3300
How efficient is the call to std::async? Can it be used to issue a task in a game loop?
I want all my input detection to be on a separate thread and synced at a certain point in the game loop in my main thread so that I can poll for input.
The only way I can think of doing this is to split up my tasks for input detection and call them using std::async
at the beginning of the actual game loop and then call wait()
later in the loop to sync the data, but I want that same behavior EVERY iteration of the loop so this call must be expensive...
Is that the way?
Upvotes: 1
Views: 1733
Reputation: 171453
Assuming it's well written then std::async(std::launch::async, ...)
should be no more expensive than a small heap allocation and constructing a std::thread
. If creating a new std::thread
to do the work is efficient enough for you, then std::async
will be efficient enough but will save you the trouble of writing the synchronisation to get the result back to the main thread.
If creating a new std::thread
for each piece of work is not appropriate, then std::async
might not be either.
(N.B. remember that unless you specify std::launch::async
as the launch policy there's no guarantee the task executes asynchronously, it might be deferred until you call get()
on the returned future.)
Upvotes: 3
Reputation: 490693
At least IMO, you should make up your mind between polling and asynchronous operation.
If you're going to poll, then using std::async
is redundant. You're going to poll from the main thread anyway, so you might as well just have it directly poll for what it cares about and be done with it. Using std::async
to launch something else will simply add a delay in getting the data to the main thread.
If you're going to use std::async
, then you should take a rather different approach: the threads that get the input act independently. When they find some input, they send it to the main thread, and tell it that it has some input to process (e.g., by setting a semaphore). Then the main thread reacts to that semaphore, retrieves the input data (e.g., from a queue) and processes it.
In the latter case, polling is pointless: if the input thread hasn't told the main thread about some input data, then there simply isn't any. That being the case, polling for input data is pointless -- you already know there is none.
Upvotes: 3