下面是一些簡單的代碼;請注意,有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 –