Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use select() instead of sleep()?

I'm working through a chapter about iPhone audio and have come across a section of code that I can't make sense of:

while (aqc.playPtr < aqc.sampleLen) 
{
    select(NULL, NULL, NULL, NULL, 1.0);
}

(Full code sample is on pages 163-166). From what I understand of the code the audio is being processed on another thread and the while loop is just there to prevent the main thread from terminating while audio is still being processed.

What I don't understand is why select() is being used instead of sleep().

From what I've read select() is used to monitor changes in I/O and passing it NULLs doesn't do anything meaningful. I've ran the code using sleep() and it works as expected. (My knowledge of low level POSIX is almost non-existant.)

like image 914
Benedict Cohen Avatar asked Jun 26 '10 22:06

Benedict Cohen


People also ask

What can I use instead of sleep in C++?

Usleep () Function The header “unistd. h” provides yet another function “usleep()” that can suspend the execution of a program for a specified period of time. The working is similar to sleep () function described already.

How does sleep () work in C?

sleep() Function in C. sleep() function in C allows the users to wait for a current thread for a specific time. Other operations of the CPU will function properly but the sleep() function will sleep the present executable for the specified time by the thread.

What does sleep () do in C ++?

The function sleep gives a simple way to make the program wait for a short interval. If your program doesn't use signals (except to terminate), then you can expect sleep to wait reliably throughout the specified interval.


2 Answers

Select allow for accurate sub second wait, and is more portable than sleep. There are other ways to wait, see this question.

But the timeout parameter of select should not be a float but a pointer to struct timeval. I'm surprised the code you show even compiles. More : this strange conditional select is followed by an unconditional sleep(1). Looks pointless to me.

like image 106
kriss Avatar answered Oct 12 '22 09:10

kriss


Using select() with NULL rfds, wfds and efds is an idiomatic way of portably sleeping with subsecond resolution.

like image 23
ninjalj Avatar answered Oct 12 '22 09:10

ninjalj