Вопрос

I have a situation where several threads write the same value to the same memory location.

Can this lead to the memory location storing a corrupt value resulting from the concurrent writes ?

Let's say I have an object of class A with a unique id. When it is used by threads, these threads will assign a certain id to them, say 100. My question is : can the id be a value other than 100 after all of the threads write 100 to this memory location? In other words, do I have to protect this id with a mutex ?

Это было полезно?

Решение

I think multiple non-atomic writes of the same value are guaranteed to be safe (i.e. producing the same result as one write) if these two conditions hold:

  • a non-atomic write is constructed from a series of atomic writes
  • several atomic writes of the same value to a location produce that same value

Both of these seem to be natural enough to expect, but I am not sure they are true for every possible implementation.

The example I am thinking of is the following:

Suppose two processes write the 2-byte value 1 to some address a. The value is written as two separate atomic bytes: 1 to address a, and 0 to address a+1. Now if we have two processes (P,Q), both writing first the value 1 to address (say) 10, then writing the value 0 to address 11, then without mutual exclusion we get the following possible executions:

  • P[1->10],P[0->11],Q[1->10],Q[0->11]
  • P[1->10],Q[1->10],P[0->11],Q[0->11]
  • P[1->10],Q[1->10],Q[0->11],P[0->11]
  • Q[1->10],Q[0->11],P[1->10],P[0->11]
  • Q[1->10],P[1->10],Q[0->11],P[0->11]
  • Q[1->10],P[1->10],P[0->11],Q[0->11]

Either way we write 1 twice to location 10, and write 0 twice to location 11 atomically. If the two writes produce the same result as one write, then either of the above sequences produces the same result.

Другие советы

Short answer: yes, be conservative and protect your critical section using a mutex. This way, you are guaranteed that your code will work correctly on every possible platform.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top