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进行进程间互斥所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)