I'm trying to fix https://gcc.gnu.org/bugzilla/show_bug.cgi?id=116586 .
Whilst fixing it for std::shared_timed_mutex I've uncovered inconsistencies
in the behaviour of the existing implementation that I think are at the
very least confusing and suboptimal. I know what I'd like to change but I'm
worried that there may be reasons not to do that.

shared_timed_mutex has four "fundamental" try_lock function implementations
for the product of steady vs system clock and exclusive vs shared. (There
are others, but they end up calling one of the four.)

1. shared_timed_mutex::try_lock_shared_until() on system_clock loops
   indefinitely if pthread_rwlock_timedrdlock() returns EDEADLK. The
   comment above justifies this by saying:

        // For cases where the implementation detects a deadlock we
        // intentionally block and timeout so that an early return isn't
        // mistaken for a spurious failure, which might help users realise
        // there is a deadlock.

   This makes some sense but shared_timed_mutex::try_lock_shared_until() on
   steady_clock, and shared_timed_mutex::try_lock_until() on both clocks
   don't loop on EDEADLK. They just return false if
   pthread_rwlock_{clockrd,clockwr,timedwr}lock() return EDEADLK. I can't
   find any other std::*mutex::try_lock_until functions that loop on
   EDEADLK.

   IMO if _GLIBCXX_ASSERTIONS are enabled then it would make more sense to
   always assert on EDEADLK instead. If the looping is a good idea, then it
   should be done in all four cases on std::shared_timed_mutex, and perhaps
   for other std::*timed_mutex classes too. If it's not a good idea, then
   the looping should be removed from this one place.

   As it stands, I'm inclined to assert on EDEADLK if _GLIBCXX_ASSERTIONS
   are enabled and not loop. But does Hyrum's Law mean that it's too late
   to change the behaviour now?

2. All the shared_timed_mutex::try_ functions that take a timeout currently
   return true (incorrectly indicating that the lock has been taken) in
   reaction to errors that aren't EAGAIN (sometimes), ETIMEDOUT or EDEADLK.
   This turns makes bugs like
   https://gcc.gnu.org/bugzilla/show_bug.cgi?id=121141 even nastier. I
   think that the functions should always return false on error since the
   lock has not been taken.

The indicative patch below implements the above (except the loop removal)
along with tests. It also has tests to show that std::*timed_mutex,
std::condition_variable and std::future don't suffer from PR116586. I plan
to add equivalent tests for std::*semaphore::try_acquire_until() too.

Thanks.

Mike.

--8<--

diff --git c/libstdc++-v3/include/std/shared_mutex 
w/libstdc++-v3/include/std/shared_mutex
index 94c8532399d..1a03fbd6a87 100644
--- c/libstdc++-v3/include/std/shared_mutex
+++ w/libstdc++-v3/include/std/shared_mutex
@@ -529,14 +529,21 @@ _GLIBCXX_BEGIN_NAMESPACE_VERSION
            static_cast<long>(__ns.count())
          };

+       if (__ts.tv_sec < 0 || __ts.tv_nsec < 0) {
+         __ts.tv_sec = 0;
+         __ts.tv_nsec = 0;
+       }
+
        int __ret = __glibcxx_rwlock_timedwrlock(&_M_rwlock, &__ts);
+       if (__ret == 0)
+         return true;
        // On self-deadlock, we just fail to acquire the lock.  Technically,
        // the program violated the precondition.
        if (__ret == ETIMEDOUT || __ret == EDEADLK)
          return false;
        // Errors not handled: EINVAL
        __glibcxx_assert(__ret == 0);
-       return true;
+       return false;
       }

 #ifdef _GLIBCXX_USE_PTHREAD_RWLOCK_CLOCKLOCK
@@ -555,15 +562,23 @@ _GLIBCXX_BEGIN_NAMESPACE_VERSION
            static_cast<long>(__ns.count())
          };

+       if (__ts.tv_sec < 0 || __ts.tv_nsec < 0) {
+         __ts.tv_sec = 0;
+         __ts.tv_nsec = 0;
+       }
+
        int __ret = pthread_rwlock_clockwrlock(&_M_rwlock, CLOCK_MONOTONIC,
                                               &__ts);
+       if (__ret == 0)
+         return true;
+
        // On self-deadlock, we just fail to acquire the lock.  Technically,
        // the program violated the precondition.
        if (__ret == ETIMEDOUT || __ret == EDEADLK)
          return false;
        // Errors not handled: EINVAL
        __glibcxx_assert(__ret == 0);
-       return true;
+       return false;
       }
 #endif

@@ -605,6 +620,11 @@ _GLIBCXX_BEGIN_NAMESPACE_VERSION
            static_cast<long>(__ns.count())
          };

+       if (__ts.tv_sec < 0 || __ts.tv_nsec < 0) {
+         __ts.tv_sec = 0;
+         __ts.tv_nsec = 0;
+       }
+
        int __ret;
        // Unlike for lock(), we are not allowed to throw an exception so if
        // the maximum number of read locks has been exceeded, or we would
@@ -619,14 +639,17 @@ _GLIBCXX_BEGIN_NAMESPACE_VERSION
        // intentionally block and timeout so that an early return isn't
        // mistaken for a spurious failure, which might help users realise
        // there is a deadlock.
-       do
+       do {
          __ret = __glibcxx_rwlock_timedrdlock(&_M_rwlock, &__ts);
-       while (__ret == EAGAIN || __ret == EDEADLK);
+         __glibcxx_assert(__ret != EDEADLK);
+       } while (__ret == EAGAIN || __ret == EDEADLK);
+       if (__ret == 0)
+         return true;
        if (__ret == ETIMEDOUT)
          return false;
        // Errors not handled: EINVAL
        __glibcxx_assert(__ret == 0);
-       return true;
+       return false;
       }

 #ifdef _GLIBCXX_USE_PTHREAD_RWLOCK_CLOCKLOCK
@@ -645,15 +668,23 @@ _GLIBCXX_BEGIN_NAMESPACE_VERSION
            static_cast<long>(__ns.count())
          };

+       if (__ts.tv_sec < 0 || __ts.tv_nsec < 0) {
+         __ts.tv_sec = 0;
+         __ts.tv_nsec = 0;
+       }
+
+       // Should we be looping on EDEADLK and EAGAIN here?
        int __ret = pthread_rwlock_clockrdlock(&_M_rwlock, CLOCK_MONOTONIC,
                                               &__ts);
+       if (__ret == 0)
+         return true;
        // On self-deadlock, we just fail to acquire the lock.  Technically,
        // the program violated the precondition.
        if (__ret == ETIMEDOUT || __ret == EDEADLK)
          return false;
        // Errors not handled: EINVAL
        __glibcxx_assert(__ret == 0);
-       return true;
+       return false;
       }
 #endif

diff --git 
c/libstdc++-v3/testsuite/30_threads/condition_variable/members/116586.c 
w/libstdc++-v3/testsuite/30_threads/condition_variable/members/116586.c
new file mode 100644
index 00000000000..e01c303f691
--- /dev/null
+++ w/libstdc++-v3/testsuite/30_threads/condition_variable/members/116586.c
@@ -0,0 +1,62 @@
+// { dg-do run { target c++11 } }
+
+#include <chrono>
+#include <mutex>
+#include <testsuite_hooks.h>
+
+namespace chrono = std::chrono;
+
+// thread.timedmutex.requirements.general:
+//   If abs_time has already passed, the function attempts to obtain
+//   ownership without blocking (as if by calling try_lock()).
+
+#if defined(_GLIBCXX_ASSERTIONS)
+#error Test cases will fail if _GLIBCXX_ASSERTIONS is enabled
+#endif
+
+template <typename Clock>
+void
+test_absolute(chrono::nanoseconds offset)
+{
+  std::mutex mtx;
+  std::condition_variable cv;
+  chrono::time_point<Clock> tp(offset);
+  std::unique_lock lock(mtx);
+  // Doesn't cope with spurious wakeup
+  VERIFY(cv.wait_until(lock, tp) == std::cv_status::timeout);
+}
+
+// The type of clock used for the actual wait depends on whether
+// _GLIBCXX_USE_PTHREAD_MUTEX_CLOCKLOCK is defined. We might as well just test
+// both steady_clock and system_clock.
+template <typename Clock>
+void
+test_relative(chrono::nanoseconds offset)
+{
+  std::mutex mtx;
+  std::condition_variable cv;
+  const auto d = -Clock::now().time_since_epoch() + offset;
+  std::unique_lock lock(mtx);
+  // Doesn't cope with spurious wakeup
+  VERIFY(cv.wait_for(lock, d) == std::cv_status::timeout);
+}
+
+int main()
+{
+  // Try once with an offset that ought to result in tv_sec == 0, tv_nsec < 0
+  // and one with an offset that ought to result in tv_sec < 0, tv_nsec == 0
+  // for the absolute calls at least.  It's not really possible to arrange for
+  // the relative calls to have tv_nsec == 0 due to time advancing.
+  for (const chrono::nanoseconds offset : {
+      // tv_sec == 0, tv_nsec < 0
+      chrono::duration_cast<chrono::nanoseconds>(chrono::milliseconds{-10}),
+      // tv_sec < 0
+      chrono::duration_cast<chrono::nanoseconds>(chrono::seconds{-10})
+    }) {
+    test_absolute<chrono::system_clock>(offset);
+    test_relative<chrono::system_clock>(offset);
+
+    test_absolute<chrono::steady_clock>(offset);
+    test_relative<chrono::steady_clock>(offset);
+  }
+}
diff --git c/libstdc++-v3/testsuite/30_threads/future/members/116586.c 
w/libstdc++-v3/testsuite/30_threads/future/members/116586.c
new file mode 100644
index 00000000000..7368cc2f99d
--- /dev/null
+++ w/libstdc++-v3/testsuite/30_threads/future/members/116586.c
@@ -0,0 +1,59 @@
+// { dg-do run { target c++11 } }
+
+#include <chrono>
+#include <mutex>
+#include <testsuite_hooks.h>
+
+namespace chrono = std::chrono;
+
+// thread.timedmutex.requirements.general:
+//   If abs_time has already passed, the function attempts to obtain
+//   ownership without blocking (as if by calling try_lock()).
+
+#if defined(_GLIBCXX_ASSERTIONS)
+#error Test cases will fail if _GLIBCXX_ASSERTIONS is enabled
+#endif
+
+template <typename Clock>
+void
+test_absolute(chrono::nanoseconds offset)
+{
+  std::promise<int> p;
+  std::future f = p.get_future();
+  const chrono::time_point<Clock> tp(offset);
+  VERIFY(f.wait_until(tp) == std::future_status::timeout);
+}
+
+// The type of clock used for the actual wait depends on whether
+// _GLIBCXX_HAVE_LINUX_FUTEX is defined.  We might as well just test both
+// steady_clock and system_clock.
+template <typename Clock>
+void
+test_relative(chrono::nanoseconds offset)
+{
+  std::promise<int> p;
+  std::future f = p.get_future();
+  const auto d = -Clock::now().time_since_epoch() + offset;
+  VERIFY(f.wait_for(d) == std::future_status::timeout);
+}
+
+int main()
+{
+  // Try once with an offset that ought to result in tv_sec == 0, tv_nsec < 0
+  // and one with an offset that ought to result in tv_sec < 0, tv_nsec == 0
+  // for the absolute calls at least.  It's not really possible to arrange for
+  // the relative calls to have tv_nsec == 0 due to time advancing.
+  for (const chrono::nanoseconds offset : {
+      // tv_sec == 0, tv_nsec < 0
+      chrono::duration_cast<chrono::nanoseconds>(chrono::milliseconds{-10}),
+      // tv_sec < 0
+      chrono::duration_cast<chrono::nanoseconds>(chrono::seconds{-10})
+    }) {
+    test_absolute<chrono::system_clock>(offset);
+    test_relative<chrono::system_clock>(offset);
+
+    test_absolute<chrono::steady_clock>(offset);
+    test_relative<chrono::steady_clock>(offset);
+  }
+  VERIFY(false);
+}
diff --git 
c/libstdc++-v3/testsuite/30_threads/recursive_timed_mutex/try_lock_until/116586.c
 
w/libstdc++-v3/testsuite/30_threads/recursive_timed_mutex/try_lock_until/116586.c
new file mode 100644
index 00000000000..99cd6b60ec9
--- /dev/null
+++ 
w/libstdc++-v3/testsuite/30_threads/recursive_timed_mutex/try_lock_until/116586.c
@@ -0,0 +1,72 @@
+// { dg-do run { target c++11 } }
+
+#include <chrono>
+#include <mutex>
+#include <testsuite_hooks.h>
+
+namespace chrono = std::chrono;
+
+// thread.timedmutex.requirements.general:
+//   If abs_time has already passed, the function attempts to obtain
+//   ownership without blocking (as if by calling try_lock()).
+
+#if defined(_GLIBCXX_ASSERTIONS)
+#error Test cases will fail if _GLIBCXX_ASSERTIONS is enabled
+#endif
+
+template <typename Clock>
+void
+test_absolute(chrono::nanoseconds offset)
+{
+  std::recursive_timed_mutex mtx;
+  chrono::time_point<Clock> tp(offset);
+  VERIFY(mtx.try_lock_until(tp));
+
+  {
+    // To test failing to lock a recursive mutex we need to try to lock on a
+    // different thread.
+    auto t = std::async(std::launch::async, [&mtx, tp]() {
+       VERIFY(!mtx.try_lock_until(tp));
+      });
+  }
+}
+
+// The type of clock used for the actual wait depends on whether
+// _GLIBCXX_USE_PTHREAD_MUTEX_CLOCKLOCK is defined. We might as well just test
+// both steady_clock and system_clock.
+template <typename Clock>
+void
+test_relative(chrono::nanoseconds offset)
+{
+  std::recursive_timed_mutex mtx;
+  const auto d = -Clock::now().time_since_epoch() + offset;
+  VERIFY(mtx.try_lock_for(d));
+
+  {
+    // To test failing to lock a recursive mutex we need to try to lock on a
+    // different thread.
+    auto t = std::async(std::launch::async, [&mtx, d]() {
+       VERIFY(!mtx.try_lock_for(d));
+      });
+  }
+}
+
+int main()
+{
+  // Try once with an offset that ought to result in tv_sec == 0, tv_nsec < 0
+  // and one with an offset that ought to result in tv_sec < 0, tv_nsec == 0
+  // for the absolute calls at least.  It's not really possible to arrange for
+  // the relative calls to have tv_nsec == 0 due to time advancing.
+  for (const chrono::nanoseconds offset : {
+      // tv_sec == 0, tv_nsec < 0
+      chrono::duration_cast<chrono::nanoseconds>(chrono::milliseconds{-10}),
+      // tv_sec < 0
+      chrono::duration_cast<chrono::nanoseconds>(chrono::seconds{-10})
+    }) {
+    test_absolute<chrono::system_clock>(offset);
+    test_relative<chrono::system_clock>(offset);
+
+    test_absolute<chrono::steady_clock>(offset);
+    test_relative<chrono::steady_clock>(offset);
+  }
+}
diff --git 
c/libstdc++-v3/testsuite/30_threads/shared_timed_mutex/try_lock_until/116586.c 
w/libstdc++-v3/testsuite/30_threads/shared_timed_mutex/try_lock_until/116586.c
new file mode 100644
index 00000000000..9d1d7b9134a
--- /dev/null
+++ 
w/libstdc++-v3/testsuite/30_threads/shared_timed_mutex/try_lock_until/116586.c
@@ -0,0 +1,96 @@
+// { dg-do run { target c++14 } }
+
+#include <chrono>
+#include <shared_mutex>
+#include <testsuite_hooks.h>
+
+namespace chrono = std::chrono;
+
+// thread.timedmutex.requirements.general:
+//   If abs_time has already passed, the function attempts to obtain
+//   ownership without blocking (as if by calling try_lock()).
+
+#if defined(_GLIBCXX_ASSERTIONS)
+#error Test cases will fail if _GLIBCXX_ASSERTIONS is enabled
+#endif
+
+template <typename Clock>
+void
+test_exclusive_absolute(chrono::nanoseconds offset)
+{
+  std::shared_timed_mutex stm;
+  chrono::time_point<Clock> tp(offset);
+  VERIFY(stm.try_lock_until(tp));
+  VERIFY(!stm.try_lock_until(tp));
+}
+
+template <typename Clock>
+void
+test_shared_absolute(chrono::nanoseconds offset)
+{
+  std::shared_timed_mutex stm;
+  chrono::time_point<Clock> tp(offset);
+  VERIFY(stm.try_lock_shared_until(tp));
+  stm.unlock_shared();
+
+  VERIFY(stm.try_lock_for(chrono::seconds{10}));
+
+  {
+    // NPTL will give us EDEADLK if pthread_rwlock_timedrdlock() is called on
+    // the same thread that already holds the exclusive (write) lock, so let's
+    // arrange for a different thread to try to acquire the shared lock.
+    auto t = std::async(std::launch::async, [&stm, tp]() {
+       VERIFY(!stm.try_lock_shared_until(tp));
+      });
+  }
+}
+
+// The type of clock used for the actual wait depends on whether
+// _GLIBCXX_USE_PTHREAD_RWLOCK_CLOCKLOCK is defined. We might as well just test
+// both steady_clock and system_clock.
+template <typename Clock>
+void
+test_exclusive_relative(chrono::nanoseconds offset)
+{
+  std::shared_timed_mutex stm;
+  const auto d = -Clock::now().time_since_epoch() + offset;
+  VERIFY(stm.try_lock_for(d));
+  VERIFY(!stm.try_lock_for(d));
+}
+
+template <typename Clock>
+void
+test_shared_relative(chrono::nanoseconds offset)
+{
+  std::shared_timed_mutex stm;
+  const auto d = -Clock::now().time_since_epoch() + offset;
+  VERIFY(stm.try_lock_shared_for(d));
+  stm.unlock_shared();
+  // Should complete immediately
+  VERIFY(stm.try_lock_for(chrono::seconds{10}));
+  VERIFY(!stm.try_lock_shared_for(d));
+}
+
+int main()
+{
+  // Try once with an offset that ought to result in tv_sec == 0, tv_nsec < 0
+  // and one with an offset that ought to result in tv_sec < 0, tv_nsec == 0
+  // for the absolute calls at least.  It's not really possible to arrange for
+  // the relative calls to have tv_nsec == 0 due to time advancing.
+  for (const chrono::nanoseconds offset : {
+      // tv_sec == 0, tv_nsec < 0
+      chrono::duration_cast<chrono::nanoseconds>(chrono::milliseconds{-10}),
+      // tv_sec < 0
+      chrono::duration_cast<chrono::nanoseconds>(chrono::seconds{-10})
+    }) {
+    test_exclusive_absolute<chrono::system_clock>(offset);
+    test_shared_absolute<chrono::system_clock>(offset);
+    test_exclusive_relative<chrono::system_clock>(offset);
+    test_shared_relative<chrono::system_clock>(offset);
+
+    test_exclusive_absolute<chrono::steady_clock>(offset);
+    test_shared_absolute<chrono::steady_clock>(offset);
+    test_exclusive_relative<chrono::steady_clock>(offset);
+    test_shared_relative<chrono::steady_clock>(offset);
+  }
+}
diff --git 
c/libstdc++-v3/testsuite/30_threads/timed_mutex/try_lock_until/116586.c 
w/libstdc++-v3/testsuite/30_threads/timed_mutex/try_lock_until/116586.c
new file mode 100644
index 00000000000..54c961eda6e
--- /dev/null
+++ w/libstdc++-v3/testsuite/30_threads/timed_mutex/try_lock_until/116586.c
@@ -0,0 +1,58 @@
+// { dg-do run { target c++11 } }
+
+#include <chrono>
+#include <mutex>
+#include <testsuite_hooks.h>
+
+namespace chrono = std::chrono;
+
+// thread.timedmutex.requirements.general:
+//   If abs_time has already passed, the function attempts to obtain
+//   ownership without blocking (as if by calling try_lock()).
+
+#if defined(_GLIBCXX_ASSERTIONS)
+#error Test cases will fail if _GLIBCXX_ASSERTIONS is enabled
+#endif
+
+template <typename Clock>
+void
+test_absolute(chrono::nanoseconds offset)
+{
+  std::timed_mutex mtx;
+  chrono::time_point<Clock> tp(offset);
+  VERIFY(mtx.try_lock_until(tp));
+  VERIFY(!mtx.try_lock_until(tp));
+}
+
+// The type of clock used for the actual wait depends on whether
+// _GLIBCXX_USE_PTHREAD_MUTEX_CLOCKLOCK is defined. We might as well just test
+// both steady_clock and system_clock.
+template <typename Clock>
+void
+test_relative(chrono::nanoseconds offset)
+{
+  std::timed_mutex mtx;
+  const auto d = -Clock::now().time_since_epoch() + offset;
+  VERIFY(mtx.try_lock_for(d));
+  VERIFY(!mtx.try_lock_for(d));
+}
+
+int main()
+{
+  // Try once with an offset that ought to result in tv_sec == 0, tv_nsec < 0
+  // and one with an offset that ought to result in tv_sec < 0, tv_nsec == 0
+  // for the absolute calls at least.  It's not really possible to arrange for
+  // the relative calls to have tv_nsec == 0 due to time advancing.
+  for (const chrono::nanoseconds offset : {
+      // tv_sec == 0, tv_nsec < 0
+      chrono::duration_cast<chrono::nanoseconds>(chrono::milliseconds{-10}),
+      // tv_sec < 0
+      chrono::duration_cast<chrono::nanoseconds>(chrono::seconds{-10})
+    }) {
+    test_absolute<chrono::system_clock>(offset);
+    test_relative<chrono::system_clock>(offset);
+
+    test_absolute<chrono::steady_clock>(offset);
+    test_relative<chrono::steady_clock>(offset);
+  }
+}

Reply via email to