Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

gh-74953: Add _PyTime_FromMicrosecondsClamp() function #93942

Merged
merged 1 commit into from
Jun 17, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions Include/cpython/pytime.h
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,10 @@ PyAPI_FUNC(_PyTime_t) _PyTime_FromSeconds(int seconds);
/* Create a timestamp from a number of nanoseconds. */
PyAPI_FUNC(_PyTime_t) _PyTime_FromNanoseconds(_PyTime_t ns);

/* Create a timestamp from a number of microseconds.
* Clamp to [_PyTime_MIN; _PyTime_MAX] on overflow. */
PyAPI_FUNC(_PyTime_t) _PyTime_FromMicrosecondsClamp(_PyTime_t us);

/* Create a timestamp from nanoseconds (Python int). */
PyAPI_FUNC(int) _PyTime_FromNanosecondsObject(_PyTime_t *t,
PyObject *obj);
Expand Down
8 changes: 8 additions & 0 deletions Python/pytime.c
Original file line number Diff line number Diff line change
Expand Up @@ -406,6 +406,14 @@ _PyTime_FromNanoseconds(_PyTime_t ns)
}


_PyTime_t
_PyTime_FromMicrosecondsClamp(_PyTime_t us)
{
_PyTime_t ns = _PyTime_Mul(us, US_TO_NS);
return pytime_from_nanoseconds(ns);
}


int
_PyTime_FromNanosecondsObject(_PyTime_t *tp, PyObject *obj)
{
Expand Down
25 changes: 9 additions & 16 deletions Python/thread_pthread.h
Original file line number Diff line number Diff line change
Expand Up @@ -438,22 +438,15 @@ PyThread_acquire_lock_timed(PyThread_type_lock lock, PY_TIMEOUT_T microseconds,

_PyTime_t timeout; // relative timeout
if (microseconds >= 0) {
_PyTime_t ns;
if (microseconds <= _PyTime_MAX / 1000) {
ns = microseconds * 1000;
}
else {
// bpo-41710: PyThread_acquire_lock_timed() cannot report timeout
// overflow to the caller, so clamp the timeout to
// [_PyTime_MIN, _PyTime_MAX].
//
// _PyTime_MAX nanoseconds is around 292.3 years.
//
// _thread.Lock.acquire() and _thread.RLock.acquire() raise an
// OverflowError if microseconds is greater than PY_TIMEOUT_MAX.
ns = _PyTime_MAX;
}
timeout = _PyTime_FromNanoseconds(ns);
// bpo-41710: PyThread_acquire_lock_timed() cannot report timeout
// overflow to the caller, so clamp the timeout to
// [_PyTime_MIN, _PyTime_MAX].
//
// _PyTime_MAX nanoseconds is around 292.3 years.
//
// _thread.Lock.acquire() and _thread.RLock.acquire() raise an
// OverflowError if microseconds is greater than PY_TIMEOUT_MAX.
timeout = _PyTime_FromMicrosecondsClamp(microseconds);
}
else {
timeout = _PyTime_FromNanoseconds(-1);
Expand Down