This is the mail archive of the
gcc-help@gcc.gnu.org
mailing list for the GCC project.
Re: pthread_cancel and C++11
- From: NightStrike <nightstrike at gmail dot com>
- To: Jonathan Wakely <jwakely dot gcc at gmail dot com>
- Cc: John Saxton <john dot saxton at elementaltechnologies dot com>, gcc-help <gcc-help at gcc dot gnu dot org>
- Date: Tue, 11 Aug 2015 21:43:31 -0400
- Subject: Re: pthread_cancel and C++11
- Authentication-results: sourceware.org; auth=none
- References: <CANZ7fQ+1h4Uw8pQ9qN8mhBkRb2d0HUGGWS2u892sBGg_wbmPHg at mail dot gmail dot com> <CAH6eHdRx19DQjAeAgw9L-nS+E0L7XMNtTC=L7FDY=ZWoSBykeQ at mail dot gmail dot com>
On Tue, Aug 11, 2015 at 10:51 AM, Jonathan Wakely <jwakely.gcc@gmail.com> wrote:
> On 10 August 2015 at 20:01, John Saxton
> <john.saxton@elementaltechnologies.com> wrote:
>> My organization recently upgraded to C++11 and we're running into a
>> problem. We use the POSIX threading library, and in some rare cases
>> (pthread_join doesn't exit within a specified timeout, for example),
>> we'll kill a thread via pthread_cancel. In C++, thread cancellation is
>> implemented via the abi::__forced_unwind exception[1], and in C++03,
>> this worked well for us.
>>
>> In C++11, all destructors are noexcept(true) by default. So if you try
>> to cancel a thread that's in a destructor, the abi::__forced_unwind
>> exception will escape the destructor, std::terminate() will be
>> invoked, and your program dies. I have written a simple program that
>> can reproduce this.[2]
>
> Yes, I've been aware of this problem for some time, and don't have any solution.
>
>> What's the best way to solve this problem? I could avoid using
>> pthread_cancel, but I was hoping to be able to upgrade to C++11
>> without making major changes like that. I could flag all my
>> destructors as noexcept(false), but that's tedious and doesn't cover
>> third party code like the STL or Boost. I briefly looked into
>> std::thread, but it looks like std::thread doesn't have a cancellation
>> mechanism. I have reproduced this with a couple of different libstdc++
>> versions (4.8.4-2ubuntu1~14.04 being the newest package I have tested
>> with). Would upgrading to a newer version fix my problem?
>
> No, the problem is inherent to using forced_unwind in C++11.
>
>> Any other
>> ideas? Do I just need to accept the fact that C++11 broke POSIX thread
>> cancellation and there's always going to be a chance that
>> pthread_cancel will cause my application to terminate?
>
> Yes, or accept that you shouldn't use pthread_cancel in C++11. I don't
> have any better suggestions, sorry.
You had a suggestion a few years ago:
https://gcc.gnu.org/ml/libstdc++/2012-12/msg00062.html