如何使线程睡眠在Windows上少于一毫秒 [英] How to make thread sleep less than a millisecond on Windows

查看:400
本文介绍了如何使线程睡眠在Windows上少于一毫秒的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Windows上我有一个问题,我从来没有遇到过Unix。这是如何让线程睡眠不到一毫秒。在Unix上,你通常有一些选择(sleep,usleep和nanosleep)来满足你的需要。然而,在Windows上,只有具有毫秒粒度的 Sleep

On Windows I have a problem I never encountered 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.

在Unix上,我可以使用 select 系统调用来创建一个微秒级的睡眠,

On Unix, I can use the use the select system call to create a microsecond sleep which is pretty straightforward:

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

如何在Windows上实现相同的功能?

How can I achieve the same on Windows?

推荐答案

在Windows上,使用 select 会强制您加入 Winsock 库,在应用程序中必须像这样初始化:

On Windows 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);

然后选择将不允许你调用没有任何套接字,因此你必须做一个再创建一个microsleep方法:

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);
}

所有这些创建的usleep方法在成功时返回零,

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

这篇关于如何使线程睡眠在Windows上少于一毫秒的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆