为什么不睡觉呢? [英] Why isn't usleep working?

查看:109
本文介绍了为什么不睡觉呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个正在单独的队列/线程上运行的函数.在此函数中,我尝试调用usleep.

I have a function that is being run on a separate queue/thread. In this function I am trying to call usleep.

不管传入的值如何,usleep似乎都不起作用. sleep()也是如此.

Regardless of the value passed in, usleep doesn't seem to work. The same goes for sleep().

为诊断错误,我打印了errno. errno打印为:系统调用中断"

To diagnose the error, I printed out errno. errno prints as: "Interrupted system call"

这到底是什么意思,我该如何诊断呢?

手册页将错误描述为:

[EINTR]            A signal was delivered to the process and its action was to invoke a signal-catching
                    function.

注意我在OSX Mountain Lion上使用Xcode 4和Objective-C.我正在使用Cocoa开发OSX应用程序.

Note I am on OSX Mountain Lion using Xcode 4 and using Objective-C. I am developing an app for OSX using Cocoa.

推荐答案

usleepsleep可以通过传递信号以这种方式中断.

usleep and sleep can be interrupted in this manner by the delivery of signals.

没有专用的信号传递线程,因此可以将信号传递到应用程序中的任意线程.

There is no dedicated signal delivery thread, so signals can be delivered to arbitrary threads in your application.

注意下面留下的原始答案在Mountain Lion上不能正常运行-在XCode下运行时,其他某些事件会触发EINTR.

Note Original answer left below does not work properly on Mountain Lion - something else is triggering the EINTR when run under XCode.

为避免此问题,我们切换到nanosleep,并使用以下事实:当中断时,它会在第二个参数中返回剩余时间:

To avoid this problem, we swap over to nanosleep, and use the fact that when it gets interrupted it returns the remaining time in the second parameter:

struct timespec to_sleep = { 1, 0 }; // Sleep for 1 second
while ((nanosleep(&to_sleep, &to_sleep) == -1) && (errno == EINTR));

尽管,如果您使用的是NSThread,那么最好使用:

Although, if you're using an NSThread, then you're better off using:

[NSThread sleepForTimeInterval:1.0f]; // sleep for 1 second

这是可可的睡眠方式,不会遭受sleepusleepnanosleep经历的打ic"

which is the Cocoa way of sleeping, and does not suffer from the 'hiccuping' that sleep, usleep and nanosleep experience

旧答案-在调试器下无法正常工作.

Old Answer - Does not work properly under the debugger.

如果要防止具有usleep的线程被中断,则需要屏蔽掉可能传递给该线程的所有信号.例如

If you want to prevent the thread that has your usleep from being interrupted, you need to mask out all the signals that may be delivered to the thread. e.g.

#include <signal.h>

sigset_t sigset;
sigset_t oldset;
sigfillset(&sigset);
pthread_sigmask(SIG_BLOCK, &sigset, &oldset);
usleep(9999);
pthread_sigmask(SIG_SETMASK, &oldset, NULL);

注意:此代码未执行错误检查

Note: No error checking done in this code

这篇关于为什么不睡觉呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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