shared memory & mutex
I've to share memory between two applications. I readed several documents about it an I find that I've to use a mutex (semaphore) to see if the shared memory is in use or not.
I wonder if I can create a structure for example:
where I set/clear semaphore variable to see if is in use or not.
I find it much more simple than using the system semphores...
Does someone can explain me if and why is better to use system semaphores and in the case, why the approach i described is not good?
You use system semaphores because your approach doesn't work. It's unsafe. Furthermore, only system semaphores allow you to actually block until the semaphore is clear.
Excuse me but I don't understand yet because my approach is unsafe.
If I check my boolean flag before use the data it's the same that if I check a system mutex...which is the difference? It's my application that wait for the semaphore, not the OS .. I believe ...
In which manner I can use the OS for waiting for semaphore?
A simple variable is not thread-safe at all, and provides no guarantee of mutual exclusion. At the very least, you need guaranteed atomic access and store/load barriers.
Also, what happens if the test tells you that you can't access the data? What do you do?