C++ Logo

std-proposals

Advanced search

Re: [std-proposals] Freestanding try_lock_for and try_lock_until

From: Howard Hinnant <howard.hinnant_at_[hidden]>
Date: Mon, 25 Aug 2025 13:41:09 -0400
Fwiw, I standardized lock/try_lock [https://eel.is/c++draft/thread.lock.algorithm]. I wanted lock, and had to implement try_lock to make it work. So since it was already there I included try_lock in the public API.

Here’s a paper that explores different implementations for lock:

https://howardhinnant.github.io/dining_philosophers.html
I don’t immediately see a reason that try_lock_for/until as you have described it wouldn’t work. The only nit I have is that if the first lock came back right at the limit, then try_locking the rest is going to go over the limit (whether successful or not).

You might be able to fix that by allowing it in the wording. Or you might find a heuristic for waiting on the first lock for a little less time so that the following try_lock is likely to fit within the temporal budget.

Howard

On Aug 18, 2025, at 5:44 PM, Ted Lyngmo via Std-Proposals <std-proposals_at_[hidden]> wrote:
>
> Hi!
>
> I wanted to create a `unique_multilock` class template with all the member functions of `unique_lock` but that is capable of locking multiple lockables like `scoped_lock`.
>
> Most of it seems pretty straight forward, but for _TimedLockable_s I realized that `std::try_lock_for`/`std::try_lock_until` are "missing".
>
> What I have in mind are two functions templates like this:
> ```
> template <class Clock, class Duration, TimedLockable... Ls>
> [[nodiscard]] bool
> try_lock_until(const std::chrono::time_point<Clock, Duration>& tp, Ls&... ls);
>
> template <class Rep, class Period, TimedLockable... Ls>
> [[nodiscard]] bool
> try_lock_for(const std::chrono::duration<Rep, Period>& dur, Ls&... ls);
> ```
> I wonder, are there any inherent reasons why we shouldn't have such function templates in the standard library? If so, I won't pursure writing a proposal. If it's just a case of "noone wanted them bad enough to write a proposal", I may go ahead.
>
> Best regards,
> Ted Lyngmo
>
> Ps. I have something of a reference implementation up for code review if you'd like to take a peek at it:
>> https://codereview.stackexchange.com/questions/297918/freestanding-try-lock-for-try-lock-until-pt-2
>
> --
> Std-Proposals mailing list
> Std-Proposals_at_[hidden]
> https://lists.isocpp.org/mailman/listinfo.cgi/std-proposals


Received on 2025-08-25 17:41:46