【问题标题】:x86 gcc sleep block or spin?x86 gcc 睡眠阻塞或自旋?
【发布时间】:2011-07-23 08:38:05
【问题描述】:

如何在 C spin 中创建一个 sleep 版本,以便它使用 cpu 周期?

【问题讨论】:

  • 所以你的问题是如何编写旋转的睡眠函数?
  • 是的,我如何使自定义睡眠功能旋转

标签: c multithreading locking x86 sleep


【解决方案1】:

您想要做的是 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】:

    我想像(伪代码)

    while (time < endtime)
        ; 
    

    “time

    【讨论】:

      【解决方案3】:

      你还需要什么吗?

      for (; ; ) ;
      

      ?

      【讨论】:

      • 大概,是的——它必须在给定的时间后返回。
      猜你喜欢
      • 1970-01-01
      • 2011-02-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-18
      • 1970-01-01
      • 1970-01-01
      • 2011-11-29
      相关资源
      最近更新 更多