Using semaphores to read and write to shared memory