问题描述
这是一道面试题.
是否可以在 Linux/UNIX 的多处理情况下使用互斥锁?
Is it possible to use mutex in multiprocessing case on Linux/UNIX ?
我的想法:不,不同的进程有不同的内存空间.
My idea:No, different processes have separate memory space.
mutex 仅用于多线程.
mutex is only used for multithreading.
信号量用于多处理以进行同步.
semaphore is used for multiprocessing to do synchronization.
对吗?
欢迎任何意见.
谢谢
推荐答案
互斥锁(mutexes)防止多线程从同时执行代码的关键部分访问共享数据(即互斥体用于序列化线程的执行).所有互斥锁必须是全局的.一个通过 mutex_lock() 成功调用互斥锁将导致另一个线程也试图锁定相同的互斥锁阻塞,直到所有者线程通过方式解锁它互斥锁().同一进程中的线程或其他进程内可以共享互斥锁.
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.
互斥锁可以同步同一进程中的线程,或者在其他进程中.互斥锁可用于同步如果互斥体分配在进程之间的线程可写内存并在协作进程之间共享(参见 mmap(2)),并已为此任务初始化.
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.
互斥体要么是进程内的,要么是进程间的,具体取决于根据隐式或显式传递给该互斥体的初始化.静态分配的互斥锁不需要显式初始化;默认情况下,一个静态分配的互斥锁用全零初始化并且它的作用域被设置在调用进程内.
Mutexes are either intra-process or inter-process, depending upon the argument passed implicitly or explicitly to the initialization of that mutex. A statically allocated mutex does not need to be explicitly initialized; by default, a statically allocated mutex is initialized with all zeros and its scope is set to be within the calling process.
对于进程间同步,需要分配互斥锁存储在这些进程之间共享的内存中.由于这种互斥体的内存必须动态分配,互斥锁需要使用 mutex_init() 显式初始化.
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().
这篇关于是否可以在 Linux/UNIX 上的多处理情况下使用互斥锁?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!