使用pthreads进行进程间互斥

使用pthreads进行进程间互斥,第1张

概述我想使用一个互斥锁,它将用于同步访问驻留在内存中的一些变量,这两个变量共享两个不同的进程.我怎样才能做到这一点.要执行的代码示例将非常感激. 使用 POSIX semaphore初始化为1. (见下文)对未命名的信号量使用sem_init,对命名的信号量使用sem_open. sem_t sem;/* initialize using sem_init or sem_open */sem_ @H_419_1@ 我想使用一个互斥锁,它将用于同步访问驻留在内存中的一些变量,这两个变量共享两个不同的进程.我怎样才能做到这一点.要执行的代码示例将非常感激.解决方法 使用 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.

总结

以上是内存溢出为你收集整理的使用pthreads进行进程间互斥全部内容,希望文章能够帮你解决使用pthreads进行进程间互斥所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1220605.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-05
下一篇 2022-06-05

发表评论

登录后才能评论

评论列表(0条)

保存