简体   繁体   中英

read() on non-blocking socket without select for low-latency

I have a separate thread reading from a non-blocking socket that I am ok with using as much CPU as necessary since low-latency is the most important aspect of the project. Would it be faster to simply loop on a read() call than use a select() first to look for sockets that are readable?

Pseudo-code:

while (!finished) {

    int rc = read(socket, buf);
    if (rc > 0) {
        // process buf
    } else if (rc == 0) {
        // eof, reconnect to server
    } else if (errno == EGAIN) {
        // nothing to do, continue
    } else if (errno == ECONNREFUSED) {
        // connection refused, attempt connect again
    } else {
        // error not yet supported
    }
}

No it wouldn't be faster, because you don't know when the data is going to arrive. So, either you will sleep for too long, which isn't faster, or you will sleep for too short, in which case you have to so it all again, which isn't faster, or you will get lucky and sleep for exactly the right time, which isn't faster and requires luck, or you won't sleep at all, which means you have to burn the CPU until the data arrives, which also isn't faster.

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