Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make select based loop as responsive as possible

This thread will be very responsive to network activity but can be guaranteed to process the message queue only as often as 100 times a second. I can keep reducing the timeout but after a certain point I will be busy-waiting and chewing up CPU. Is it true that this solution is about as good as I'll get without switching to another method?

// semi pseudocode
while (1) {
  process_thread_message_queue(); // function returns near-instantly
  struct timeval t;
  t.tv_sec = 0;
  t.tv_usec = 10 * 1000; // 10ms = 0.01s
  if (select(n,&fdset,0,0,t)) // see if there are incoming packets for next 1/100 sec
  {
    ... // respond with more packets or processing
  }
}
like image 601
Steven Lu Avatar asked Aug 10 '26 04:08

Steven Lu


1 Answers

It depends on what your OS provides for your. On Windows you can wait for a thread message and a bunch of handles simultaneously using MsgWaitForMultipleObjectsEx. This solves your problem. On other OS you should have something similar.

like image 52
Yakov Galka Avatar answered Aug 11 '26 19:08

Yakov Galka



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!