When a thread needs to change the state of a shared resource it must get exclusive access to the resource in order to prevent other threads from accessing data under construction.
However, any number of threads can read a resource. For example, any number of rendering windows can read and render the same scene simultaneously.
Realsoft 3D semaphores support this through exclusive and shared locking.
A semaphore is created:
#include <oops/r3semaph.h> sem = R3New(R3CLID_SEMAPHORE, R3TAG_END);
To get exclusive access:
R3DoA(sem, R3SEMM_OBTAIN, (void *)R3SEMM_EXCLUSIVE);
Exclusive access should only be used when one needs to change the data arbitrated via the semaphore.
To get shared access:
R3DoA(sem, R3SEMM_OBTAIN, (void*)R3SEMM_SHARED);
Shared access should be used when a thread only 'reads' a common resource. This allows any number of threads to obtain the semaphore simultaneously without blocking each other. Shared access will block only if someone other has obtained the semaphore exclusively.
It is also possible to test whether or not the semaphore is locked:
obtained = R3DoA(sem, R3SEMM_ATTEMPT, (void *)R3SEMM_EXCLUSIVE);
If the semaphore cannot be locked (another thread already has obtained it), FALSE is returned. Otherwise the semaphore is locked and true is returned.
Semaphores support nested locking. In other words, if a certain thread has already locked a certain semaphore, it can lock it again as many times as needed.