Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
469 views
in Technique[技术] by (71.8m points)

c - What Can I Use Besides usleep in a Modern POSIX Environment?

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.

implicit declaration of function ‘usleep’

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.

EDIT:

My includes are:

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

And I'm invoking the compiler with:

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

EDIT #2:

I've created a new file that contains:

#include <unistd.h>

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

And I still get the warning.

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);
}

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

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

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...