下面是一些简单的代码;请注意,有printf
声明之前有一个致电waitFor()
。为什么程序停止三秒钟,然后然后打印该消息?Printf不按程序顺序执行
int main(int argc, char* argv)
{
producer();
return 0;
}
void waitFor(unsigned int secs) {
unsigned int retTime = time(0) + secs; // Get finishing time.
while (time(0) < retTime); // Loop until it arrives.
}
static void *producer()
{
int s = 3;
printf("Busy for %d seconds", s);
waitFor(s);
return NULL;
}
谢谢你,吉姆。因为这个答案,我使用了'waitFor'例程http://stackoverflow.com/questions/3930363/implement-time-delay-in-c/3930477#3930477 – 8protons
吉姆鲍德温,是否有C系统在睡眠冲洗( )电话? AFAIK,至少libc/gcc和MSVC只在满缓冲区或显式调用时刷新。对于他们来说,忙碌循环或睡眠()将不起作用。 – theamk
奇怪。在等待期间让CPU(并让其他线程运行)更好,这就是睡眠的作用。这个waitFor()正在打击将调用资源的time()调用。仅供参考:https://linux.die.net/man/3/sleep –