x86 gcc睡眠块还是旋转?

时间:2011-03-26 04:20:14

标签: c multithreading locking x86 sleep

如何在C旋转中创建一个睡眠版本,以便它使用cpu循环?

3 个答案:

答案 0 :(得分:4)

我想像(伪代码)

while (time < endtime)
    ; 

“time&lt; endtime”的实现依赖于操作系统,但您只想在循环开始之前根据参数计算结束时间,然后连续获取系统时间并将其与结束时间进行比较。

答案 1 :(得分:2)

你想要做的是busy wait,你循环直到经过一定的时间。只需获取当前时间(使用可用的最高精度计时器)并循环,直到当前时间是您启动后的一定时间。

以下是使用Windows API和性能计数器的一个具体示例,它使用两个相关函数QueryPerformanceCounter()QueryPerformanceFrequency()

void Sleep_spin(DWORD dwMilliseconds)
{
    LARGE_INTEGER freq, target, current;

    /* get the counts per second */
    if (!QueryPerformanceFrequency(&freq)) { /* handle error */ }

    /* set target to dwMilliseconds worth of counts */
    target.QuadPart = freq.QuadPart * dwMilliseconds / 1000;

    /* get the current count */    
    if (!QueryPerformanceCounter(&current)) { /* handle error */ }

    /* adjust target to get the ending count */
    target.QuadPart += current.QuadPart;

    /* loop until the count exceeds the target */
    do
    {
        if (!QueryPerformanceCounter(&current)) { /* handle error */ }
    } while (current.QuadPart < target.QuadPart);
}

在您的情况下使用适当的API,无论可能是什么。

答案 2 :(得分:0)

除了

之外,你还需要什么吗?
for (; ; ) ;