简体   繁体   中英

sem_destroy a semaphore someone else holds a sem_wait on?

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 (eg 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:

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM