简体   繁体   中英

Winsock2 select() function: passing {0, 0} as timeout parameter

I'm creating a multiplayer real-time game based on client-server model using the <winsock2.h> library. For the communication part, I've decided to use non-blocking sockets, instead of blocking sockets to eliminate multi-threading. On the client side, I would like to handle these tasks in one single loop:

  • Handling user input (if necessary)
  • Sending/receiving data to/from the server (if possible)
  • Updating game data (with a constant frequency)
  • Refreshing the screen (with a constant frequency)

I'm wondering, if it is a bad practice to call select with a timeout {0, 0} in the second part of the loop? I found this website which says:

The timeout value {0, 0} indicates select() will return immediately, allowing an application to poll on the select() operation. This should be avoided for performance reasons.

I don't really understand, why I should avoid using it. If someone could explain, I would appreciate it.

I don't really understand, why I should avoid [calling select() with a zero-timeout). If someone could explain, I would appreciate it.

If your thread's event-loop never blocks anywhere then you will be spinning the CPU at 100% CPU usage. This is inefficient, since you'll be wasting trillions of CPU cycles pointlessly spinning around your event loop at maximum speed while not actually doing any work, and therefore all those CPU cycles will be unavailable for use elsewhere (eg by other programs or other threads in your own program). This will also generate excess heat and (on a laptop or other portable device) drain the battery very quickly.

A better approach is to calculate when you need select() to wake up (eg how much time is left between now and then next time you need to draw a frame, or do some other scheduled task), and then pass in that amount of time to select's timeout parameter. That will cause select() to block (for up to the amount of time you specified) and therefore allow your thread to sleep during the period when it doesn't need to be doing anything. That will make the difference between a program that always uses all of (at least) one entire CPU core and one that uses only the minimum amount of CPU time that it actually needs to accomplish its tasks.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM