Reputation: 6008
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:
Upvotes: 3
Views: 1805
Reputation: 147
It depends on the implementation. Some will unlock the process blocking by the semaphore and set errno to EINVAL. Some will not. I did some experiment on the Linux. The result is inconsistent. Sometimes the other process will block indefinitely. Sometimes it will be unlocked but no errno is set. I guess on Linux it is really a undefined behavior.
Upvotes: 0
Reputation: 22261
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:
So what were they trying to achieve?
I don't know.
shouldn't that be very unsafe?
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.
Upvotes: 3