简体   繁体   English

sem_destroy 其他人持有 sem_wait 的信号量?

[英]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?如果您有一个线程(thread1)阻塞在sem_wait() ,另一个线程(thread2)使用sem_destroy()销毁该信号量,那么 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.销毁其他进程或线程当前被阻塞的信号量(在 sem_wait(3) 中)会产生未定义的行为。

But, I happened to see this being used in many multi-threaded c++ applications.但是,我碰巧在许多多线程 C++ 应用程序中看到了它。

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.在我听说过的任何 API 中,我想不出一个案例,其中在使用过程中销毁某些东西是理智的或已定义的。 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.有些人会通过信号量解锁进程阻塞并将 errno 设置为 EINVAL。 Some will not.有些不会。 I did some experiment on the Linux.我在 Linux 上做了一些实验。 The result is inconsistent.结果不一致。 Sometimes the other process will block indefinitely.有时另一个进程会无限期地阻塞。 Sometimes it will be unlocked but no errno is set.有时它会被解锁但没有设置 errno。 I guess on Linux it is really a undefined behavior.我猜在 Linux 上这确实是一种未定义的行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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