If you have a thread (thread1) blocking on a sem_wait() and another thread (thread2) destroying that very semaphore, using sem_destroy(), then what happens to thread1?
A quick search on the internet tells me that it produces undefined behavior:
Destroying a semaphore that other processes or threads are currently blocked on (in sem_wait(3)) produces undefined behavior.
But, I happened to see this being used in many multi-threaded c++ applications.
My main questions:
- Could there be any purpose in this?
- What were they trying to achieve (e.g. will this implicitly terminate the thread)?
- Shouldn’t that be very unsafe?
I can’t think of a single case in any API I’ve ever heard of where destroying something while it is in the middle of being used is sane or defined. So in my opinion the answers to your questions are:
I don’t know.
Yes!
Maybe the authors of those other programs you’ve looked at are aware of what the implementations actually do and are relying on it. But they have to be prepared for the possibility that it will change in the future. Maybe they have weighed the risk of such a change breaking their programs against the savings they achieved by taking a shortcut and relying on the undefined behaviour and have judged it to be worth it. You have to make that judgement for yourself.