向条件变量发出信号(pthreads)

发布于 2024-10-20 04:38:01 字数 616 浏览 0 评论 0原文

假设某个条件变量“cond”与互斥变量“mutex”相关联。如果一个线程在调用 pthread_cond_wait(&cond,&mutex) 后在 cond 上休眠,并且另一个锁定了 mutex 的线程已完成,该线程在调用 pthread_mutex_unlock(&mutex) 之前还是之后调用 pthread_cond_signal(&cond) 有关系吗?如果调用 pthread_cond_signal(&cond) ,是否需要解锁互斥锁,因为睡眠线程无论如何都会获取互斥锁?

编辑:根据 https://computing.llnl.gov/tutorials/pthreads/#ConVarOverview,“调用 pthread_cond_signal() 后未能解锁互斥锁可能不允许匹配的 pthread_cond_wait() 例程完成(它将保持阻塞状态)。”我想那时需要解锁,也许只有在解锁之后才需要。

Suppose some condition variable "cond" is associated with a mutex variable "mutex". If a thread is sleeping on cond after calling pthread_cond_wait(&cond,&mutex), and another thread that has mutex locked is finished, does it matter whether that thread calls pthread_cond_signal(&cond) before or after calling pthread_mutex_unlock(&mutex) ? Does it even need to unlock the mutex at all if it calls pthread_cond_signal(&cond), since the sleeping thread will acquire the mutex anyway?

EDIT: According to https://computing.llnl.gov/tutorials/pthreads/#ConVarOverview, "Failing to unlock the mutex after calling pthread_cond_signal() may not allow a matching pthread_cond_wait() routine to complete (it will remain blocked)." I guess then, unlocking, and perhaps only afterwards, is required.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

满天都是小星星 2024-10-27 04:38:01

您应该始终在调用 pthread_cond_signal 后解锁互斥锁。以下是一些值得阅读的好问题/答案:

在不锁定互斥体的情况下调用 pthread_cond_signal

我现在不会想到这一点,但我很确定有一个很好的理由(就竞争条件而言)您不想在发出信号之前解锁互斥体。

You should always unlock the mutex after calling pthread_cond_signal. Here are some good questions/answers to read:

Calling pthread_cond_signal without locking mutex

It won't come to me right now, but I'm pretty sure there's a good reason (in terms of race conditions) that you don't want to unlock the mutex before signalling.

初见你 2024-10-27 04:38:01

如果保持互斥锁锁定,则被唤醒的线程无法获取互斥锁,因此将阻塞在 pthread_cond_wait 等待重新获取互斥锁。

您无需保持互斥体锁定即可调用pthread_cond_signal。事实上,如果您的应用程序逻辑可以在互斥锁未锁定时使用信号,那么这是一个更好的方法——操作系统可以立即调度等待线程,而不必等待信号线程在继续之前解锁互斥体。

但是,在这种情况下,必须注意确保唤醒不会丢失,并且不会出现“错误”线程被唤醒的问题。如果您使用直接的谓词,这在实践中应该不是问题。

If you keep the mutex locked, then the thread being woken cannot acquire the mutex, so will block in pthread_cond_wait waiting to reacquire the mutex.

You do not need to hold the mutex locked to call pthread_cond_signal. In fact, if your application logic can work with a signal when the mutex is not locked then that is a better way to do it --- the OS can schedule the waiting thread immediately, and it doesn't have to wait for the signalling thread to unlock the mutex before proceeding.

However, in this scenario care must be taken to ensure that the wake-up is not lost, and you don't have a problem with the "wrong" thread being woken. If you use a straight-forward predicate, this shouldn't be a problem in practice.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文