sem_init(...):pshared 参数有什么用? [英] sem_init(...): What is the pshared parameter for?
问题描述
在研究生课程中,我们不得不使用信号量来完成线程工作.
In a graduate class, we've had to use semaphores to accomplish work with threads.
我们被指示将 sem_init
与其他一些 sem_* 过程一起使用,但我们没有得到关于这些 sem_* 方法中每一个的详细信息的太多信息.
We were directed to use sem_init
along with a bunch of other sem_* procedure but we were not given much information about the details of each of these sem_* methods.
sem_init
的原型(和头文件)是 以下:
The prototype (and header file) of sem_init
is the following:
#include <semaphore.h>
int sem_init(sem_t *sem, int pshared, unsigned int value);
但我不明白 pshared 值的用途.根据 opengroup.org:
but I don't understand what the pshared value is used for. According to opengroup.org:
如果 pshared
参数有一个非零值,然后共享信号量进程之间;在这种情况下,任何可以访问信号量的进程sem
可以使用 sem
来执行sem_wait()
、sem_trywait()
、sem_post()
、和 sem_destroy()
操作.
If the
pshared
argument has a non-zero value, then the semaphore is shared between processes; in this case, any process that can access the semaphoresem
can usesem
for performingsem_wait()
,sem_trywait()
,sem_post()
, andsem_destroy()
operations.
但我想我不明白 1,2, 10, 25, 50000 等之间的区别.我认为这是说如果值为 0 则不共享信号量.(但是,重点是什么?)
but I guess I don't understand the difference between say 1,2, 10, 25, 50000, etc. I think it is saying that if the value is 0 then the semaphore is not shared. (But then, what is the point?)
如何恰当地使用这个 pshared
参数?
How do I appropriately use this pshared
parameter?
推荐答案
sem_init
的 GLIBC 版本(如果你在 Linux 上 man sem_init
会得到什么)有这个说:
The GLIBC version of sem_init
(what you get if you man sem_init
on Linux) has this to say:
"pshared 参数表明这个信号量是否被在进程的线程之间或进程之间共享."
"The pshared argument indicates whether this semaphore is to be shared between the threads of a process, or between processes."
所以 pshared
是一个布尔值:实际上传递给它的有意义的值是 false
(0
) 和 true
(1
),但任何非 0 值都将被视为真.如果传递它 0,您将获得一个信号量,该信号量可以被同一进程中的其他线程访问——本质上是一个进程内锁.您可以将其用作互斥锁,也可以更广泛地将其用于信号量的资源计数属性.可以说,如果 pthreads 支持信号量 API,你就不需要 sem_init
的这个特性,但是 Unix 中的信号量比 pthreads 早了很多时间.
So pshared
is a boolean value: in practice meaningful values passed to it are false
(0
) and true
(1
), though any non-0 value will be treated as true. If you pass it 0 you will get a semaphore that can be accessed by other threads in the same process -- essentially an in-process lock. You can use this as a mutex, or you can use it more generally for the resource-counting properties of a semaphore. Arguably if pthreads supported a semaphore API you wouldn't need this feature of sem_init
, but semaphores in Unix precede pthreads by quite a bit of time.
如果布尔值是某种枚举会更好(例如 SEM_PROCESS_PRIVATE
与 SEM_PROCESS_SHARED
),因为那样你就不会遇到这个问题,但是 POSIX 信号量随着这些事情的发展,它们是一个相当古老的 API.
It would be better if the boolean was some kind of enumeration (e.g. SEM_PROCESS_PRIVATE
vs SEM_PROCESS_SHARED
), because then you wouldn't have had this question, but POSIX semaphores are a fairly old API as these things go.
这篇关于sem_init(...):pshared 参数有什么用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!