Being Cellfish

Stuff I wished I've found in some blog (and sometimes did)

Sleep less than one millisecond

Change of Address
This blog has moved to blog.cellfish.se.

Sleep less than one millisecond

  • Comments 1

On windows you have a problem you typically never encounter on Unix. That is how to get a thread to sleep for less than one millisecond. On Unix you typically have a number of choices (sleep, usleep and nanosleep) to fit your needs. On windows however there is only Sleep with millisecond granularity. You can however use the select system call to create a microsecond sleep. On Unix this is pretty straight forward:

int usleep(long usec)
{
    struct timeval tv;
    tv.tv_sec = usec/1000000L;
    tv.tv_usec = usec%1000000L;
    return select(0, 0, 0, 0, &tv);
}

On windows however, the use of select forces you to include the winsock library which has to be initialized like this in your application:

    WORD wVersionRequested = MAKEWORD(1,0);
    WSADATA wsaData;
    WSAStartup(wVersionRequested, &wsaData);

And then the select won't allow you to be called without any socket so you have to do a little more to create a microsleep method:

int usleep(long usec)
{
    struct timeval tv;
    fd_set dummy;
    SOCKET s = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
    FD_ZERO(&dummy);
    FD_SET(s, &dummy);
    tv.tv_sec = usec/1000000L;
    tv.tv_usec = usec%1000000L;
    return select(0, 0, 0, &dummy, &tv);
}

All these created usleep methods return zero when successful and non-zero for errors.

 

  • I recently described how you can create your own usleep method when there isn't one to use. one thing

Page 1 of 1 (1 items)