user3037172
user3037172

Reputation: 587

executing a command on a variable used by multiple threads

Given the threading scenario where two threads execute the computation:

 x = x + 1 where x is a shared variable

What are the possible results and describe why your answer could happen.

This is a textbook problem from my OS book and I was curious if I needed more information to answer this such as what x is initialized too and how often the threads execute this command or just once. My answer originally was that it could be two possible answers depending on the order that the threads execute them by the OS.

Upvotes: 0

Views: 32

Answers (1)

Calum
Calum

Reputation: 2130

This is a rather simple task, so there isnt probably too much that could go wrong.

The only issue i can immediately think of is if one thread uses on old value of x in its calculation.

eg:

start with x = 2

1) thread A reads x = 2

2) thread B reads x = 2

3) thread A writes x = 2 + 1

x = 3

4) thread B writes x = 2(old value of x) + 1

x = 3 when it should be 4

this would be even more apparent if more than 1 thread reads the value before the first thread writes.

Upvotes: 1

Related Questions