Scrolling flows - what possible results can be displayed

Take this topic:

a = 3; b is 3;

And take this thread:

b is 5; a = 5;

They both use the same data from the monitor.

If they both start at the same time (using threads), what results are possible?

+6
source share
1 answer

Since thread operations can be performed in any order, any combination of a = 3.5 and b = 3.5 is possible.

To clarify for future readers:

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

Possible operational orders:

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's 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 order of threads, you would have reached such a result ~ 67% of the time. However, you have no guarantee of this probability; in fact, you can be almost sure that the OS is biased in some unknown way. The lesson is that you should not rely on undefined behavior to do ANYTHING for you.

(I know that the last part went a little beyond the scope of the question, but I think she means it.)

+6
source

All Articles