使用 sleep() 或无限循环等待事件更好吗?

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

我目前正在开发与 SSH 服务器通信的客户端。 一切正常,但是,由于服务器响应速度很慢,我必须等待它发送数据。 我有两个选择,我想请教一下什么是最有效的等待服务器的方式。

选择 #1:

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

选项 #2:

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

您可能想调用 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

另请查看 libssh poll functions

我认为使用 sleep 而不是无限循环,因为使用无限循环会浪费 CPU 能量和时间。使用 sleep 时,CPU 将能够 运行 其他程序。

这两种选择都是不可取的。通常,您会使用阻塞读取。我假设它看起来像这样(因为你说你正在等待服务器):

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

在这种情况下,poll 是不必要的。只需确保 SSH 连接是 blocking 连接,如果 none 在您调用时可用,read 函数将等待数据可用。

// This is all you need.
ssh_channel_read(...);

剪辑不是一个好主意。 使用 sleep(...) 你几乎不会像使用 empty while(...).

那样使用你的 cpu