如何同步两个进程访问同一资源?
我有两个进程访问相同的物理内存(GPIO 数据地址)。 那么如何在这些应用程序之间进行同步呢? 我知道我们有某种锁定机制,例如互斥锁和信号量,那么哪种方法最快?
谢谢你的帮助,
-nm
I have two processes which access to the same physical memory(GPIO data addr).
So how can I have synchronized between these apps?
I understand that we have some kind of locking mechanism such as mutex and semaphore, so which method is the fastest?
Thank for your help,
-nm
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
互斥体和信号量通常被认为是同一地址空间中的并发解决方案 - 这意味着同一程序的不同部分将使用这些装置之一锁定对资源的访问。
当您处理单独的进程时,在 Linux 上执行此操作的标准方法是在
/var/lock
中创建一些内容,例如/var/lock/myapp.lock
,并将您的 PID 放在其中,后跟换行符。然后其他进程将检查它是否存在,如果您很狡猾,请检查 PID 以确保它仍然存在。如果您需要实时访问该区域,请跳过文件系统,进程必须通过 IPC 进行通信(
LET_ME_KNOW_WHEN_DONE
、OKAY_IM_DONE
,您明白了),或者 - - 更好 - 编写一个进程,其唯一目的是读取和写入 GPIO 内存,并且您的其他程序通过 IPC 与它通信(可能是最好的方法)。Mutexes and semaphores are generally considered to be concurrency solutions in the same address space -- meaning that different parts of the same program will lock their access to a resource using one of these contraptions.
When you're dealing with separate processes, the standard way to do this on Linux is to create something in
/var/lock
, like/var/lock/myapp.lock
, and place your PID followed by a newline in it. Then other processes will check for its existence, and if you're crafty check the PID to make sure it's still alive, too.If you need real-time access to the area, skip the filesystem and the processes will have to communicate via IPC (
LET_ME_KNOW_WHEN_DONE
,OKAY_IM_DONE
, you get the idea), or -- better -- write a process whose sole purpose is to read and write to the GPIO memory, and your other programs communicate with it via IPC (probably the best approach).互斥意味着互斥——信号量只是一个用于确定资源是否正在使用的变量。在Windows中,可以创建一个Mutex对象来保护共享资源。
问题是你使用什么语言?什么操作系统(我假设是linux)。大多数语言都提供对多线程和互斥的支持,您应该使用内置的构造。
例如,在 Linux 上使用 C,您可能需要
包含 semaphore.h
并查找 sem_init、sem_wait 等的调用。
mutex means mutual exclusion -- a semaphore is just a variable used to determine if the resource is in use. In windows, there is a Mutex object that can be created to protect a shared resource.
The issue is what language are you using? What OS (I am assuming linux). Most languages provide support for multi-threading and mutual exclusion, and you should use the built-in constructs.
For example, using C on Linux, you might want to
include semaphore.h
and look up the calls for sem_init, sem_wait etc.