Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Threads interleaving - what possible results could be output

Take this thread:

a = 3; b = 3;

And take this thread:

b = 5; a = 5;

They both access the same data from a Monitor.

If they both run concurrently (by using threads), what outcomes are possible?

like image 945
Rhys Avatar asked Jan 12 '13 20:01

Rhys


People also ask

What is interleaving in threading?

Interference happens when two operations, running in different threads, but acting on the same data, interleave. This means that the two operations consist of multiple steps, and the sequences of steps overlap.

What problem can occur when two threads share memory?

Thread Interference Error. When multiple threads share the same memory, there is a chance that two or more different threads performing different operations on the same data interleave with each other and create inconsistent data in the memory.

What is thread interference give an example?

Thread interference in java is a condition which occurs when more than one threads, executing simultaneously, access same piece of data. When more than one threads have access to same data, it is possible that data may get corrupted or one may not get the desired output.

Can there be a problem if two threads access the same memory?

If the data we share is read-only data, there will be no problem, because the data read by one thread is unaffected by whether or not another thread is reading the same data. However, once data is shared between threads, and one or more threads start modifying the data, and that's the start of problems.


1 Answers

Because the threads' operations can be performed in any order, any combination of a=3,5 and b=3,5 are possible.

To clarify for future readers:

Thread-1: a=3 b=3, Thread-2: b=5 a=5

Operational orders possible:

I: Thread-1, Thread-1, Thread-2, Thread-2

II: Thread-1, Thread-2, Thread-1, Thread-2

III: Thread-1, Thread-2, Thread-2, Thread-1

IV: Thread-2, Thread-1, Thread-2, Thread-1

V: Thread-2, Thread-2, Thread-1, Thread-1

VI: Thread-2, Thread-1, Thread-1, Thread-2

Let us try each:

I: a=3, b=3, b=5, a=5 --> a=5, b=5

II: a=3, b=5, b=3, a=5 --> a=5, b=3

III: a=3, b=5, a=5, b=3 --> a=5, b=3

IV: b=5, a=3, a=5, b=3 --> a=5, b=3

V: b=5, a=5, a=3, b=3 --> a=3, b=3

VI: b=5, a=3, b=3, a=5 --> a=5, b=3

Note that there are four ways to come up with a=5,b=3. Thus if you had a fair probability of each thread ordering, you would come up with that result ~67% of the time. However, you have no guarantees of such a probability; in fact, you can be almost certain that the OS is biased in some unknown manner. The lesson is, you should not try to rely on undefined behavior to do ANYTHING for you.

(I know that last part was a little beyond the scope of the question but I think it bears keeping in mind.)

like image 99
BlackVegetable Avatar answered Oct 13 '22 18:10

BlackVegetable