is it better to use sleep() or an infinite loop to wait for an event?

1.9k views Asked by At

I'm currently working on a client that talk with a SSH server. Everything works well, but, because the server is quite slow to answer, I have to wait for it to send data. I have two choices, and I'd like to have your advice about what is the most efficient way to wait for the server.

Choice #1 :

while (!(ssh_channel_poll(*sshChannel,0)))
 ;

Choice #2 :

while (!(ssh_channel_poll(*sshChannel,0)))
  sleep(1);
4

There are 4 answers

4
Dietrich Epp On BEST ANSWER

Both alternatives are undesirable. Normally, you would use a blocking read. I assume it looks something like this (since you say you are waiting for the server):

while (!ssh_channel_poll(...)) { ... }
ssh_channel_read(...);

In this case, the poll is unnecessary. Just make sure the SSH connection is a blocking connection, and the read function will wait until data is available if none is available when you call it.

// This is all you need.
ssh_channel_read(...);
0
Basile Starynkevitch On

You probably want to call the poll(2) system call (or the old select(2) one). Then you need to get the relevant file descriptor. Or use the ssh_channel_poll_timeout function or ssh_channel_select.

Look also into libssh poll functions.

2
msc On

I think use sleep instead of infinite loop because using infinite loop, you are wasting CPU Power and time. When using sleep, the CPU will be able to run other programs.

0
Maksym Bodnar On

Clipping is not a good idea. With sleep(...) you don't use hardly your cpu like with empty while(...).