https://gcc.gnu.org/bugzilla/show_bug.cgi?id=103382

            Bug ID: 103382
           Summary: condition_variable::wait() is not cancellable because
                    it is marked noexcept
           Product: gcc
           Version: 10.2.0
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: libstdc++
          Assignee: unassigned at gcc dot gnu.org
          Reporter: vanyacpp at gmail dot com
  Target Milestone: ---

At the moment condition_variable::wait() is marked noexcept. It means that if
pthread_cond_wait() acts as cancellation point and throws an exception the
program is terminated with std::terminate(). This program demonstrates the
issue:

#include <condition_variable>
#include <thread>

int main()
{
    std::mutex m;
    std::condition_variable cv;

    std::thread th([&]
    {
        std::unique_lock lock(m);
        cv.wait(lock);
    });

    pthread_cancel(th.native_handle());
    th.join();
}

This program terminates with SIGABRT.

Because of this using condition_variable::wait() in cancellable threads is
tricky: the programmer has to guard all calls to condition_variable::wait()
with disabling/restoring cancellation state. Also this stops the thread from
being cancellable while in wait(). Therefore the outer thread has to know which
condition_variable the thread waits and notify this condition_variable after
pthread_cancel(). Also one should add cancellation point pthread_testcancel()
immediately after restoring cancellation state after wait().

I believe it would be great if condition_variable::wait interacted nicer with
POSIX-cancellation. I would like to suggest removing noexcept from
condition_variable::wait(). This also matches the C++ standard very well
[thread.condition.condvar] where condition_variable::wait() is not marked as
noexcept.

Reply via email to