我可以用另外usleep在现代POSIX环境? [英] What Can I Use Besides usleep in a Modern POSIX Environment?

查看:321
本文介绍了我可以用另外usleep在现代POSIX环境?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是相当新的C,但写一个小多线程应用程序。我想介绍一个延迟一个线程。使用'usleep我一直和行为是我的愿望 - 但它在C99产生警告

I'm fairly new to C but writing a small multithreaded application. I want to introduce a delay to a thread. I'd been using 'usleep' and the behavior is what I desire - but it generates warnings in C99.

函数隐式声明'usleep

implicit declaration of function ‘usleep’

这只是一个警告,但它困扰我。我GOOGLE了一个答案,但所有我能找到的是,似乎这将是CPU密集型一个while循环/定时器方法。

It's only a warning, but it bothers me. I've Googled for an answer but all I could find was a while-loop / timer approach that seemed like it would be CPU intensive.

编辑:

我的是包括:

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include <time.h>

和我调用的编译器:

c99 program.c -Wall -pedantic -W -lpthread

编辑#2:

我已经创建了一个包含一个新的文件:

I've created a new file that contains:

#include <unistd.h>

int main(void) {
    usleep(10);
}

和我仍然得到警告。

编辑#3:
至于建议,我已经更新了问题的文本。

EDIT #3: As suggested, I've updated the text of the question.

推荐答案

的问题是,您使用的是标准的C99编译的,但你要访问POSIX扩展。揭露POSIX扩展,你应该例如定义为_POSIX_C_SOURCE 200809L(当前标准)。例如此程序:

The problem is that you are using a standard C99 compiler, but you're trying to access POSIX extensions. To expose the POSIX extensions you should for example define _POSIX_C_SOURCE to 200809L (for the current standard). For example this program:

#include <time.h>

int main(void) {
        struct timespec reqtime;
        reqtime.tv_sec = 1;
        reqtime.tv_nsec = 500000000;
        nanosleep(&reqtime, NULL);
}

将正确编译和下面的编译命令等待1.5秒(1秒+ 5亿纳秒):

will compile correctly and wait for 1.5 seconds (1 second + 500000000 nanoseconds) with the following compilation command:

c99 main.c -D _POSIX_C_SOURCE=200809L

该_POSIX_C_SOURCE宏必须有一个适当的值来定义的POSIX扩展可用于

The _POSIX_C_SOURCE macro must be defined with an appropriate value for the POSIX extensions to be available.

此外-Wall,-pedantic和-W不为POSIX C99命令定义的选项,这些看起来更像是海湾合作委员会的命令,我(如果你的系统上工作,那么这很好,要知道,他们是不能移植到其他POSIX系统)。

Also the options -Wall, -pedantic and -W are not defined for the POSIX c99 command, those look more like gcc commands to me (if they work on your system then that's fine, just be aware that they are not portable to other POSIX systems).

这篇关于我可以用另外usleep在现代POSIX环境?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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