문제

void Wait(double Duration)
{
    clock_t End;
    End = clock() + (Duration*CLOCKS_PER_SEC);

    while (clock() < End)
    {
        // This loop just stalls the program.
    }
}

My function works perfectly half the time, but it occasionally stalls the program before it's even called. For example, take the following snippet:

cout << "This is\n";
Wait(2.5)
cout << "a test!";

You'd expect the first line to appear immediately and the second line to appear after 2.5 seconds, but it sometimes ALL appears after 2.5 seconds. What's the deal?

도움이 되었습니까?

해결책

try

cout.flush();

before your Wait

다른 팁

That might be because of I/O buffering. You should flush the output buffer (either try << endl instead of '\n' or writing cout.flush) manually.

Try cout << "This is" << endl;

It looks like a buffering, not clock issue.

The flush()/std::endl has already been mentioned - but is your intention to really consume 100% of one core while you wait? This is what the while() loop is doing! If you want a nicer approach to "waiting", consider one of the following:

  1. boost::thread::sleep() - millisecond granularity
  2. alarms (1 second granularity)
  3. select()
  4. pthread_cond_timedwait()

etc.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top