今天在看hypertable的异步通讯库的过程中发现,usleep, sleep 函数会重置 clock的返回值,很是奇怪。
这里记录一下,再给一个例子:
下面的代码是能正常运行的,但是当我调整了sleep的位置后,程序就永远不能动了。
#include <stdio.h>
#include <time.h>
#include <unistd.h>
void wait ( int seconds )
{
clock_t endwait;
endwait = clock () + seconds * CLOCKS_PER_SEC ;
while (clock() < endwait) {
}
}
int main ()
{
int n;
printf ("Starting countdown...\n");
for (n=10; n>0; n--)
{
printf ("%d\n",n);
wait (1);
usleep(10);
}
printf ("FIRE!!!\n");
return 0;
}
#include <unistd.h>
void wait ( int seconds )
{
clock_t endwait;
endwait = clock () + seconds * CLOCKS_PER_SEC ;
while (clock() < endwait) {
}
}
int main ()
{
int n;
printf ("Starting countdown...\n");
for (n=10; n>0; n--)
{
printf ("%d\n",n);
wait (1);
usleep(10);
}
printf ("FIRE!!!\n");
return 0;
}
#include <stdio.h>
#include <time.h>
#include <unistd.h>
void wait ( int seconds )
{
clock_t endwait;
endwait = clock () + seconds * CLOCKS_PER_SEC ;
while (clock() < endwait) {
usleep(10);
}
}
int main ()
{
int n;
printf ("Starting countdown...\n");
for (n=10; n>0; n--)
{
printf ("%d\n",n);
wait (1);
}
printf ("FIRE!!!\n");
return 0;
}
#include <unistd.h>
void wait ( int seconds )
{
clock_t endwait;
endwait = clock () + seconds * CLOCKS_PER_SEC ;
while (clock() < endwait) {
usleep(10);
}
}
int main ()
{
int n;
printf ("Starting countdown...\n");
for (n=10; n>0; n--)
{
printf ("%d\n",n);
wait (1);
}
printf ("FIRE!!!\n");
return 0;
}