加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

使用pthreads进行进程间互斥

发布时间:2020-12-16 10:29:31 所属栏目:百科 来源:网络整理
导读:我想使用一个互斥锁,它将用于同步访问驻留在内存中的一些变量,这两个变量共享两个不同的进程.我怎样才能做到这一点.要执行的代码示例将非常感激. 解决方法 使用 POSIX semaphore初始化为1. (见下文)对未命名的信号量使用sem_init,对命名的信号量使用sem_open
我想使用一个互斥锁,它将用于同步访问驻留在内存中的一些变量,这两个变量共享两个不同的进程.我怎样才能做到这一点.要执行的代码示例将非常感激.

解决方法

使用 POSIX semaphore初始化为1. (见下文)对未命名的信号量使用sem_init,对命名的信号量使用sem_open.

sem_t sem;

/* initialize using sem_init or sem_open */

sem_wait(&sem);
/* critical region */
sem_post(&sem);

在最初发布此答案多年后,必须对其进行更新.

实际应该使用互斥锁而不是信号量. R和kuga的评论(下面逐字复制)解释了原因.特别是我发现kuga提到互斥锁只能通过锁定线程发布最引人注目的.

[R

sem_init requires a nonzero pshared argument to be shared,just like a
mutex would require the pshared attribute. There’s no reason to prefer
semaphores over mutexes for this,and in fact mutexes would be better
because you could use a robust mutex which allows you to handle the
(very real!) case where one process dies while holding the lock.

玖珂

Additionally to R..`s post,a mutex can only be posted by the thread that locks it. This is often required and a semaphore does not provide this feature. So this is not the correct answer,Jeff′s answer should be flagged as the correct answer.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读