0

Actually I would like to know the issues caused by independent concurrent writes to shared memory.

To be more elobarote, consider we have three processes (proc1, proc2, proc3). These 3 processes are trying to use a ring buffer based on shared memory IPC. When proc1 makes concurrent writes to ring buffer acquiring a lock, what happens to proc2 and proc3 waiting on the lock. The proc1 will obviously hold up proc2 and proc3, preventing their other activities.

Can anyone help me in explaining, what are all the problems we face in the above scenario and what could be an efficient solution for that?

Thanks in advance!

1 Answer 1

0

The problem with these three processes would be that they could clobber each other's data. Your ring buffer has a read index variable, a write index variable, and, say, 10 locations.

Let's say the index variable points to location #4.

Let's say process 1 wants to add to the buffer. So process one retrieves the write index variable, writes its data to location 4, and increments the write index, so it is now #5. So far, everything works beautifully.

Now processes 2 and 3 both want to add to the buffer. Process 2 retrieves the write index and sees #5. Process 3 retrieves the write index and also sees #5. Then process 2 writes its data to location 5, but that is immediately destroyed by process 3 (which saw the same location after all!) Finally, process 2 and 3 both increment the write index. Depending on timing and your exact implementation, the write index may then end up being either 6 or 7.

One solution to this problem is to make the whole operation atomic - meaning that process 3 does not get to do anything on the ring buffer until process 2 has finished. That's what a lock does.

2
  • Thanks for your answer, What happens when process 2 tries to acquire the lock for long time. process 3 has to wait on the lock? does it decrease the performance of the system? Commented Jan 23, 2018 at 5:28
  • When programming, you have a number of rules of thumb to follow. One of them "only keep locks as short as possible". Keeping a lock longer than necessary is usually considered a bug. There are other possible bugs here, BTW: deadlocks and race conditions. A race condition means that you forgot to use a lock (such as in my example). A deadlock means that two locks interact with each other so that both (or more) processes can never reach the unlock, and are permanently blocked. Commented Jan 23, 2018 at 17:33

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.