I have an application that runs multiple threads which are sometimes cancelled. These threads may call into another object that internally accesses a resources (socket). To prevent the resource to be accessed simultaneously, there is a critical section to get some order in the execution.
Now, when cancelling the thread, it (sometimes) happens that the thread is just within that code that is blocked by the critical section. The critical section is locked using an object and I was hoping that upon cancellation of the thread this object would be destructed and consequently release the lock. However this does not seem to be the case, so that at thread destruction this resource object is permanently locked.
Changing the resource object is probably not an option (3rd party delivered), plus it makes sense to prevent simultaneous access to a resource that can not be used in parallel.
I have experimented with preventing the thread to be cancelled using pthread_setcancelstate when the section is locked/unlocked, however this does feel a bit dirty and would not be a final solution for other situations (e.g. aquired mutexes, etc).
I know that a prefered solution would be to not use pthread_cancel but instead set a flag in the thread and it would cancel itself when it is ready (in a clean way). However as I want to cancel the thread asap, I was wondering (also out of academic interest) if there would be other options to do that.