sem_init(…): What is the pshared parameter for?

丶灬走出姿态 提交于 2019-12-05 00:42:55
quark

The GLIBC version of sem_init (what you get if you man sem_init on Linux) has this to say:

"The pshared argument indicates whether this semaphore is to be shared between the threads of a process, or between processes."

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.

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.

I would say that there is no significant difference between the value s 1, 2, 5 and so on with respect to the shared parameter. Probably it is written that way because when the API was first created, C did not have boolean types.

The pshared argument indicates whether this semaphore is to be shared between the threads of a process, or between processes.

If pshared has the value 0, then the semaphore is shared between the threads of a process, and should be located at some address that is visible to all threads (e.g., a global variable, or a variable allocated dynamically on the heap).

If pshared is nonzero, then the semaphore is shared between processes, and should be located in a region of shared memory (see shm_open(3), mmap(2), and shmget(2)). (Since a child created by fork(2) inherits its parent's memory mappings, it can also access the semaphore.) Any process that can access the shared memory region can operate on the semaphore using sem_post(3), sem_wait(3), etc.

The pshared argument indicates whether this semaphore is to be shared between the threads of a process, or between processes.If pshared has the value 0, then the semaphore is shared between the threads of a process, and should be located at some address that is visible to all threads.If pshared is nonzero, then the semaphore is shared betweenprocesses, and should be located in a region of shared memory.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!