Thanks to visit codestin.com
Credit goes to github.com

Skip to content

<condition_variable>: condition_variable_any::wait_until may cause infinite wait #3756

@achabense

Description

@achabense

The following code will cause infinite wait (unexpectedly).

#include<thread>
#include<condition_variable>
#include<mutex>

int main() {
	using namespace std;
	using ull_sec = std::chrono::duration<unsigned long long>;
	auto ull_point_sec = chrono::time_point_cast<ull_sec>(chrono::system_clock::now());
	std::this_thread::sleep_for(2s);

	std::mutex m;
	std::unique_lock lock{m};
	std::condition_variable_any cond;
	cond.wait_until(lock, ull_point_sec);//infinite wait.
}

In this case, in wait_until, _Abs_time - _Clock::now() will result in a large unsigned value. A quick fix would be adding a comparison before calling wait_for (return at once if _Abs_time <= now).

In the current implementation, there are both wait_until calling wait_for(see below) and wait_for calling wait_until(example). For better consistency and conformance to the standard(ref), a thorough fix would be ensuring that every wait_for will call a matching wait_until.

template <class _Lock, class _Clock, class _Duration>
cv_status wait_until(_Lock& _Lck, const chrono::time_point<_Clock, _Duration>& _Abs_time) {
// wait until time point
#if _HAS_CXX20
static_assert(chrono::is_clock_v<_Clock>, "Clock type required");
#endif // _HAS_CXX20
return wait_for(_Lck, _Abs_time - _Clock::now());
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't workingfixedSomething works now, yay!

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions