前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Condition Lock

Condition Lock

作者头像
lesM10
发布2019-08-26 16:45:04
6560
发布2019-08-26 16:45:04
举报

Well, conditional variables allow you to wait for certain condition to occur. In practice your thread may sleep on conditional variable and other thread wakes it up.

Conditional variable also usually comes with mutex. This allows you to solve following synchronisation problem: how can you check state of some mutex protected data structure and then wait until it's state changes to something else. I.e.

/* in thread 1 */
pthread_mutex_lock(mx); /* protecting state access */
while (state != GOOD) {
    pthread_mutex_unlock(mx);
    wait_for_event();
    pthread_mutex_lock(mx);
}
pthread_mutex_unlock(mx);


/* in thread 2 */
pthread_mutex_lock(mx); /* protecting state access */
state = GOOD;
pthread_mutex_unlock(mx);
signal_event(); /* expecting to wake thread 1 up */

This pseudocode sample carries a bug. What happens if scheduler decides to switch context from thread 1 to thread 2 after pthread_mutex_unlock(mx), but before wait_for_event(). In this case, thread 2 will not wake thread 1 and thread 1 will continue sleeping, possibly forever.

Conditional variable solves this by atomically unlocking the mutex before sleeping and atomically locking it after waking up. Code that works looks like this:

/* in thread 1 */
pthread_mutex_lock(mx); /* protecting state access */
while (state != GOOD) {
    pthread_cond_wait(cond, mx); /* unlocks the mutex and sleeps, then locks it back */
}
pthread_mutex_unlock(mx);

/* in thread 2 */
pthread_mutex_lock(mx); /* protecting state access */
state = GOOD;
pthread_cond_signal(cond); /* expecting to wake thread 1 up */
pthread_mutex_unlock(mx);

摘录自Stack Overflow

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019.07.14 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档