4

On my computer, running on Windows 7, the following code, compiled in Visual C++ 2010 with Boost 1.53, outputs

no timeout
elapsed time (ms): 1000

The same code compiled with GCC 4.8 (online link) outputs

timeout
elapsed time (ms): 1000

My opinion is that the VC++ output is not correct and it should be timeout. Does anyone have the same output (i.e. no timeout) in VC++? If yes, then is it a bug in the Win32 implementation of boost::condition_variable?

The code is

#include <boost/thread.hpp>
#include <iostream>

int main(void) {
  boost::condition_variable cv;
  boost::mutex mx;
  boost::unique_lock<decltype(mx)> lck(mx);
  boost::chrono::system_clock::time_point start = boost::chrono::system_clock::now();
  const auto cv_res = cv.wait_for(lck, boost::chrono::milliseconds(1000));
  boost::chrono::system_clock::time_point end = boost::chrono::system_clock::now();
  const auto count = (boost::chrono::duration_cast<boost::chrono::milliseconds>(end - start)).count();
  const std::string str = (cv_res == boost::cv_status::no_timeout) ? "no timeout" : "timeout";
  std::cout << str << std::endl;
  std::cout << "elapsed time (ms): " << count << std::endl;
  return 0; 
}
4

1 回答 1

6

If we read the documentation we see:

Atomically call lock.unlock() and blocks the current thread. The thread will unblock when notified by a call to this->notify_one() or this->notify_all(), after the period of time indicated by the rel_time argument has elapsed, or spuriously... [Emphasis mine]

What you are almost certainly seeing is that the VS implementation is treating it as a spurious wakeup that happens to be at the end of the expected duration while the other implementation is treating it as a timeout.

于 2013-04-16T18:15:53.670 回答