Multithreading for time sensitive input... or not

Started by
12 comments, last by Hawkblood 7 years ago

By background thread do you mean simply spawning a thread at the start of the application and using that to make API calls while the rest of the application runs? That would still be multithreading though right, The things I've been hearing horror stories about?


Yeah. Don't worry about it in this case though. It won't be too hard for this purpose.

As long as you carefully manage how you access data on each thread, it's unlikely that anything bad would happen. There are only two things you're dealing with in this case: a queue of input, and a flag to exit the background thread when the main thread wants it to shut down.

A simple pseudocode implementation would be:

// start this function as a thread during app startup
void InputReadingThreadFunction()
{
  while (main thread has not requested that the input thread terminate) // probably OK with a normal bool with no special synchronization
  {
    if input is available in XInput
    {
      put that input into a synchronized queue
    }
  }
}

void MainThreadInputPollingFunction()
{
  // Do this instead of reading from XInput on your main thread
  while (input is available in synchronized queue)
  {
    Process that input
  }
}
The type of queue, variables, etc depend on the language and APIs you have available.
Advertisement

Alright, I'm feeling a lot better about this now! Doesn't seem like attempting anything too crazy.

Thanks everybody, you've been a real help!

But also bear in mind that collecting input immediately on a background thread and then handing it to the main thread later is not going to get you the input any quicker than collecting it on the main thread. The only benefit is that you might have been able to get a more accurate timestamp when you received the input; but some input APIs will have already collected that data for you anyway, meaning a single-threaded approach is sufficient.

I didn't see anyone asking what the input is for..... Why do you need it so "precise"?

If you are running at 60fps consistently and it drops to 30fps at some random time for a few seconds, that's still only 16.67ms difference. If the player can detect an input difference in 16.67ms, then the player is a freakin robot.

You *can* multithread the input, but you would want to declare any variables used to store the state of such input as "volatile". This will allow your main thread to view the data without releasing it from the detached thread. I'm in agreement with Kylotan. No matter if you poll the input in a detached thread or in the main thread, you will still be handling it at the frame rate of the main thread.....

This topic is closed to new replies.

Advertisement