Milad Naseri
Milad Naseri

Reputation: 4118

Concurrent/Asynchronous access to shared data

I searched around a bit, but could not find anything useful. Could someone help me with this concurrency/synchronization problem?

Given five instances of the program below running asynchronously, with s being a shared data with an initial value of 0 and i a local variable, which values are obtainable by s?

for (i = 0; i < 5; i ++) {
    s = s + 1;
}
  1. 2
  2. 1
  3. 6

I would like to know which values, and why exactly.

Upvotes: 0

Views: 133

Answers (1)

Damon
Damon

Reputation: 70186

The non-answering answer is: Uaaaagh, don't do such a thing.

An answer more in the sense of your question is: In principle, any value is possible, because it is totally undefined. You have no strict guarantee that concurrent writes are atomic in any way and don't result in complete garbage.
In practice, less-than-machine-word sized writes are atomic everywhere (for what I know, at least), but they do not have a defined order. Also, you usually don't know in which order threads/processes are scheduled. So you will never see a "random garbage" value, but also you cannot know what it will be. It will be anything 5 or higher (up to 25).

Since no atomic increment is used, there is a race between reading the value, incrementing it, and writing it back. If the value is being written by another instance before the result is written back, the write (and thus increment) that finished earlier has no effect. If that does not happen, both increments are effective.

Nevertheless, each instance increments the value at least 5 times, so apart from the theoretical "total garbage" possibility, there is no way a value less than 5 could result in the end. Therefore (1) and (2) are not possible, but (3) is.

Upvotes: 1

Related Questions