views:

150

answers:

2

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

A: 

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).

Jed Smith
mutexes and semaphores certainly can be used cross-process. the lock file approach is going to be slower than either.
ysth
In particular, POSIX mutexes and condition variables on Linux support shared memory, with `pthread_mutexattr_setpshared` and friends. This is probably the lowest-overhead IPC mechanism available on Linux. However it is a good bit more complex to use properly.
bdonlan
Thank for your help.
nm
A: 

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.

Larry Watanabe
The question is tagged Linux.
Jed Smith