I'm building a multithreaded application with pthreads
and need a thread to periodically check some stuff. During the time in between this thread shouldn't use any CPU. Is this possible with usleep()
? Is usleep()
not busy waiting? Or is there a better solution?
相关问题
- Multiple sockets for clients to connect to
- Is shmid returned by shmget() unique across proces
- What is the best way to do a search in a large fil
- glDrawElements only draws half a quad
- Index of single bit in long integer (in C) [duplic
The function
usleep
has been removed from SUSv4. You should probably usenanosleep
instead or timers (setitimer
, etc).As R.. notes in the comments, should the sleep be implemented as a busy wait:
Thus:
It's worth mentioning that Wine (lazily?) implements usleep as a call to select():
It's also worth mentioning that nanosleep (in glibc) appears to be little more than an empty function call (anything else, and the delay might shift into the microsecond range).
(
usleep
is not part of the C standard, but of an ancient POSIX standard. But see below.)No, the POSIX specification of
usleep
clearly statesso this clearly requires that it suspends execution and lets the resources to other processes or threads.
As already be mentioned by others, the POSIX function
nanosleep
is now replacingusleep
and you should use that. C (since C11) has a functionthrd_sleep
that is modeled afternanosleep
.Just be aware that both usleep() and nanosleep() can be interrupted by a signal. nanosleep() lets you pass in an extra timespec pointer where the remaining time will be stored if that happens. So if you really need to guarantee your delay times, you'll probably want to write a simple wrapper around nanosleep().
Beware that this is not tested, but something along these lines:
And if you ever need to wake the thread for something other than a periodic timeout, take a look at condition variables and
pthread_cond_timedwait()
.On Linux, it is implemented with the nanosleep system call which is not a busy wait.
Using strace, I can see that a call to
usleep(1)
is translated intonanosleep({0, 1000}, NULL)
.usleep()
is a C runtime library function built upon system timers.nanosleep()
is a system call.Only MS-DOS, and like ilk, implement the sleep functions as busy waits. Any actual operating system which offers multitasking can easily provide a sleep function as a simple extension of mechanisms for coordinating tasks and processes.