是否可以在Linux/UNIX上的多处理案例中使用互斥?

use*_*288 24 multithreading synchronization mutex semaphore multiprocessing

这是一个面试问题.

是否可以在Linux/UNIX上的多处理案例中使用互斥?

我的想法:不,不同的进程有独立的内存空间.

mutex仅用于多线程.

信号量用于多处理以进行同步.

对 ?

欢迎任何评论.

谢谢

小智 28

 Mutual exclusion locks (mutexes)  prevent  multiple  threads
 from simultaneously executing critical sections of code that
 access shared data (that is, mutexes are used  to  serialize
 the  execution  of  threads).  All mutexes must be global. A
 successful call for a mutex lock  by  way  of   mutex_lock()
 will  cause  another  thread that is also trying to lock the
 same mutex to block until the owner thread unlocks it by way
 of   mutex_unlock().  Threads  within  the  same  process or
 within other processes can share mutexes.

 Mutexes can synchronize threads within the **same  process**  or
 in  ***other   processes***.  Mutexes  can  be used to synchronize
 threads between processes if the mutexes  are  allocated  in
 writable  memory  and shared among the cooperating processes
 (see mmap(2)), and have been initialized for this task.
Run Code Online (Sandbox Code Playgroud)

初始化互斥锁是进程内或进程间,具体取决于隐式或显式传递给该互斥锁初始化的参数.静态分配的互斥锁不需要显式初始化; 默认情况下,静态分配的互斥锁初始化为全零,其范围设置为在调用进程内.

 For inter-process synchronization, a mutex needs to be allo-
 cated   in  memory shared between these processes. Since the
 memory for such a mutex must be allocated dynamically,   the
 mutex needs to be explicitly initialized using mutex_init().
Run Code Online (Sandbox Code Playgroud)

  • 另外,对于进程间同步,除了要在共享内存中分配的要求外,互斥锁还必须使用属性PTHREAD_PROCESS_SHARED,否则从其创建者之外的其他进程访问互斥锁会导致未定义的行为(请参阅:http:// linux .die.net/man/3/pthread_mutexattr_setpshared):"进程共享属性设置为PTHREAD_PROCESS_SHARED,以允许任何可以访问分配互斥锁的内存的线程对互斥锁进行操作,即使互斥锁是在多个进程共享的内存中分配" (11认同)

Max*_*kin 9

很有可能使用进程共享的互斥锁.

事实上,现代应用程序更喜欢使用进程共享互斥锁以及信号量上的进程共享条件变量,因为后者不太灵活.

我记得在2004年使用Red Hat Linux,当时它支持进程共享互斥锁和条件变量.


pax*_*blo 5

不完全的.POSIX线程具有进程共享属性的概念,可用于创建可由多个进程操作的互斥锁.

您可以将这样的互斥锁放在共享内存中,以便多个进程都能获得它.

LINUX是否实现了这一点,我不确定,我从来没有需要使用它,因为它似乎不必要的复杂.

有关属性的有用精确度,请参阅我对此问题的回答.