简体   繁体   English

为while循环创建超时的最简洁方法是什么?

[英]What is the cleanest way to create a timeout for a while loop?

Windows API/C/C++ Windows API / C / C ++

1. ....  
2. ....
3. ....    
4.    while (flag1 != flag2)
5.    {
6.      SleepEx(100,FALSE);   
        //waiting for flags to be equal (flags are set from another thread).
7.    }
8. .....
9. .....  

If the flags don't equal each other after 7 seconds, I would like to continue to line 8. 如果标志在7秒后不相等,我想继续第8行。

Any help is appreciated. 任何帮助表示赞赏。 Thanks. 谢谢。

If you are waiting for a particular flag to be set or a time to be reached, a much cleaner solution may be to use an auto / manual reset event. 如果您正在等待设置特定标志或达到时间,则更清洁的解决方案可能是使用自动/手动重置事件。 These are designed for signalling conditions between threads and have very rich APIs designed on top of them. 这些设计用于线程之间的信令条件,并且具有在其上设计的非常丰富的API。 For instance you could use the WaitForMultipleObjects API which takes an explicit timeout value. 例如,您可以使用WaitForMultipleObjects API,它采用显式超时值。

Do not poll for the flags to change. 不要轮询要更改的标志。 Even with a sleep or yield during the loop, this just wastes CPU cycles. 即使在循环期间出现睡眠或产量,这也只会浪费CPU周期。

Instead, get the thread which sets the flags to signal you that they've been changed, probably using an event . 相反,获取设置标志的线程会发出信号通知您已经更改过,可能是使用了一个事件 Your wait on the event takes a timeout, which you can tweak to allow waiting of 7 seconds total. 你等待事件需要超时,你可以调整以允许等待7秒。

For example: 例如:

Thread1:

 flag1 = foo;
 SetEvent(hEvent);


 Thread2:

 DWORD timeOutTotal = 7000;  // 7 second timeout to start.
 while (flag1 != flag2 && timeOutTotal > 0)
 {
     // Wait for flags to change
     DWORD start = GetTickCount();

     WaitForSingleObject(hEvent, timeOutTotal);

     DWORD end = GetTickCount();

    // Don't let timeOutTotal accidently dip below 0.
    if ((end - start) > timeOutTotal)
    {
        timeOutTotal = 0;
    }
    else
    {
       timeOutTotal -= (end - start);
    }

 }

You can use QueryPerformanceCounter from WinAPI. 您可以使用WinAPI中的QueryPerformanceCounter Check it before while starts, and query if the amount of time has passed. 在开始之前检查它,并查询是否已经过了一段时间。 However, this is a high resolution timer. 但是,这是一个高分辨率计时器。 For a lower resolution use GetTickCount (milliseconds). 对于较低分辨率,请使用GetTickCount (毫秒)。

All depends whether you are actively waiting (doing something) or passively waiting for an external process. 所有这些都取决于您是在积极等待(做某事)还是被动地等待外部过程。 If the latter, then the following code using Sleep will be a lot easier: 如果是后者,则使用Sleep的以下代码将更容易:

int count = 0;
while ( flag1 != flag2 && count < 700 )
{
   Sleep( 10 ); // wait 10ms
   ++count;
}

If you don't use Sleep (or Yield) and your app is constantly checking on a condition, then you'll bloat the CPU the app is running on. 如果您不使用Sleep(或Yield)并且您的应用程序不断检查某个条件,那么您将使应用程序运行的CPU膨胀。

If you use WinAPI extensively, you should try out a more native solution, read about WinAPI's Synchronization Functions . 如果您广泛使用WinAPI,您应该尝试更原生的解决方案,阅读有关WinAPI的同步功能

You failed to mention what will happen if the flags are equal. 你没有提到如果标志相等将会发生什么。

Also, if you just test them with no memory barriers then you cannot guarantee to see any writes made by the other thread. 此外,如果您只是在没有内存屏障的情况下测试它们,那么您无法保证看到其他线程所做的任何写入。

Your best bet is to use an Event, and use the WaitForSingleObject function with a 7000 millisecond time out. 最好的办法是使用一个Event,并使用WaitForSingleObject函数,超时时间为7000毫秒。

确保你在那里做一个sleep()yield() ,否则你会吃掉所有整个CPU(或核心)等待。

我会说“检查时间,如果七秒钟后没有发生任何事情,那么就打破循环。

如果您的应用程序执行某些网络工作,请查看POSIX select()调用,尤其是超时功能!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 检索数组的最干净方法是什么? - What is the cleanest way of retrieving an array? 定义无删除指针的最干净方法是什么? - What is the cleanest way of defining a no-delete pointer? 将类型名称传递给lambda的最干净方法是什么? - What's the cleanest way to pass a typename into a lambda? 扩展此设计用于树重写的最干净方法是什么? - What is the cleanest way to extend this design for tree-rewriting? 指导wxWidgets始终使用wxFileConfig的最干净方法是什么? - What is the cleanest way to direct wxWidgets to always use wxFileConfig? 将42010958毫秒转换为Hours:Minutes:Seconds in Qt的最干净方法是什么? - What is the cleanest way to translate 42010958 Milliseconds to Hours:Minutes:Seconds in Qt? 使用迭代器遍历和取消遍历 std::vector 的最干净的方法是什么? - What's the cleanest way to walk and unwalk a std::vector using iterators? 在C ++中用字符串连接const char *的最干净方法是什么? - what is the cleanest way to concat a const char * with a string in c++? 在VC ++ Express中包含和访问二进制数据的最简洁方法是什么? - What is the cleanest way to include and access binary data in VC++ Express? 用回调函数中断while循环的最佳方法是什么? - What is the best way to break a while loop with a callback function?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM