问题描述
到目前为止,我几乎在线阅读的几乎所有代码和教程都涉及使用互斥体和信号量在线程之间进行同步.它们可以用于在进程之间进行同步吗?
Almost all the code and tutorials that I have read online so far involve using mutexes and semaphores for synchronisation amongst threads. Can they be used to synchronise amongst processes?
我想编写如下代码:
void compute_and_print() {
// acquire mutex
// critical section
// release mutex
}
void main() {
int pid = fork();
if ( pid == 0 ) {
// do something
compute_and_print();
}
else {
// do something
compute_and_print();
}
}
- 有人可以指出我这样做的类似代码吗?
- 我知道不同的进程具有不同的地址空间,但是我想知道上面是否是不同的地址空间,但是互斥锁是否会引用相同的内核对象?
推荐答案
需要明确的是,POSIX(和linux)支持两个信号量系列,它们具有两种不同的接口和使用方法.
Just to be clear, POSIX (and linux) support two separate families of semaphores that have two different interfaces and methods of usage.
有些较旧的SysV信号量由semget
,semop
,semctl
和(有些可选)ftok
组成.
There is the older SysV semaphores consisting of semget
, semop
, semctl
and (somewhat optionally) ftok
.
更现代的"posix"信号灯由sem_open/sem_init
,sem_wait
,sem_post
,sem_close
和sem_unlink
组成.
The more modern "posix" semaphores consist of sem_open/sem_init
, sem_wait
, sem_post
, sem_close
and sem_unlink
.
设置/使用方式和功能之间的差异足够大,因此有必要对两者进行熟悉,以了解哪种情况对您的用例更好.
The setup/usage regimes and capabilities are different enough that it is worth familiarizing yourself with both to see what is better for your use case.
您还可以使用pthreads软件包中的进程共享互斥锁.
You can also use process shared mutexes from the pthreads package.
这篇关于在进程中使用互斥/信号量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!