作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
在研究生类(class)中,我们不得不使用信号量来完成线程工作。
我们被指示使用 sem_init
以及一堆其他 sem_* 过程,但我们没有得到关于每个 sem_* 方法的详细信息的太多信息。sem_init
的原型(prototype)(和头文件)是 the following :
#include <semaphore.h>
int sem_init(sem_t *sem, int pshared, unsigned int value);
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.
pshared
范围?
最佳答案
sem_init
的 GLIBC 版本(如果你在 Linux 上使用 man sem_init
,你会得到什么)有这样的说法:
"The pshared argument indicates whether this semaphore is to be shared between the threads of a process, or between processes."
pshared
是一个 bool 值:实际上传递给它的有意义的值是
false
(
0
) 和
true
(
1
),尽管任何非 0 值都将被视为真。如果您将其传递为 0,您将获得一个信号量,该信号量可以被同一进程中的其他线程访问——本质上是一个进程内锁。您可以将其用作互斥体,也可以将其更广泛地用于信号量的资源计数属性。可以说,如果 pthreads 支持信号量 API,您将不需要
sem_init
的此功能。 ,但 Unix 中的信号量在 pthread 之前相当长一段时间。
SEM_PROCESS_PRIVATE
与
SEM_PROCESS_SHARED
)会更好,因为那样你就不会有这个问题了,但是 POSIX 信号量是一个相当古老的 API,因为这些事情发生了。
关于multithreading - sem_init(...) : What is the pshared parameter for?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1291566/
我是一名优秀的程序员,十分优秀!