4 ms·
Thread cancellation works fine in C++. You just need to make sure cancellable syscalls do not happen in destructors. (Which you probably want to do anyways, si
by otabdeveloper4 3y ago
Thread cancellation works fine in C++.
You just need to make sure cancellable syscalls do not happen in destructors. (Which you probably want to do anyways, since cancellable syscalls can cause errors that are difficult to handle in destructors.)
Good practice is to move destructed objects to a "garbage collection" thread which calls the real destructors and cannot be cancelled.
- ta8645 3y agoThat contradicts the assertion made in the article: Well, since thread cancellation is implemented using exceptions, and thread cancellation can happen in arbitrary places, we’re always liable to a cancellation happening in a noexcept block, which is undefined behavior, and which in practice will cause your program to crash. So since C++11, and especially since C++14 where destructors are marked as noexcept by default, thread cancellation is essentially useless in C++
- deleted 3y ago[deleted]
- otabdeveloper4 3y agoThe article is kinda useless, to be honest. Seems to be some sort of advanced blog spam and not somebody speaking from real experience. Anyways, pthread_cancel can be of two types - asynchronous or deferred. Deferred is when cancellation happens only during a system call. It's the default and what you want. (You don't want the asynchronous mode.) Under the hood thread cancellation is a C++ exception, so you still get RAII, etc.
- corsix 3y agoclose() is documented as a cancellation point, and is the kind of syscall that might crop up in a destructor.
- otabdeveloper4 3y agoIndeed a tricky point, but like I said - move these objects to another garbage collection thread and call close() there. (You probably want to do this regardless, because close() is not actually always an instanteneous syscall and can take a long time.)