std::jthread::operator=(std::jthread&&) calls std::terminate if *this has an associated running thread.

Paul Scharnofske asynts@gmail.com
Fri Nov 6 21:49:09 GMT 2020


You are correct, I was not aware of this 
(https://stackoverflow.com/a/36393265/8746648).

Here is the simplified patch (mirror: 
https://static.asynts.com/2020/11/06/jthread-0002.patch):

diff --git a/libstdc++-v3/ChangeLog b/libstdc++-v3/ChangeLog
index 89f9f6c8c38..02e4c3cc8a6 100644
--- a/libstdc++-v3/ChangeLog
+++ b/libstdc++-v3/ChangeLog
@@ -1,3 +1,8 @@
+2020-11-06  Paul Scharnofske  <asynts@gmail.com>
+
+       * include/std/thread (operator=(std::jthread&&): Join current 
thread if it
+       is running before moving it.
+
  2020-11-05  Marek Polacek  <polacek@redhat.com>

         PR c++/25814
diff --git a/libstdc++-v3/include/std/thread 
b/libstdc++-v3/include/std/thread
index 887ee579962..a5d60fe7f9f 100644
--- a/libstdc++-v3/include/std/thread
+++ b/libstdc++-v3/include/std/thread
@@ -456,7 +456,18 @@ _GLIBCXX_BEGIN_NAMESPACE_VERSION
      operator=(const jthread&) = delete;

      jthread&
-    operator=(jthread&&) noexcept = default;
+    operator=(jthread&& __other) noexcept
+    {
+      if (joinable())
+        {
+          request_stop();
+          join();
+        }
+
+      swap(__other);
+
+      return *this;
+    }

      void
      swap(jthread& __other) noexcept

On 11/6/20 10:35 PM, Ville Voutilainen wrote:
> On Fri, 6 Nov 2020 at 23:14, Paul Scharnofske via Libstdc++
> <libstdc++@gcc.gnu.org> wrote:
>>       +          // The C++ Standard (working draft) says that this
>> method must be
>>       +          // noexcept, but also dictates that join be called. It
>> doesn't say
>>       +          // how to do this, this is probably the way to go?
>>       +          try
>>       +            {
>>       +              join();
>>       +            }
>>       +          catch (...)
>>       +            {
>>       +              std::terminate();
>>       +            }
>>       +        }
> Just calling join() will have the same effect, without having to
> bother with the additional catching.



More information about the Libstdc++ mailing list