Martin Odersky: Working to make everything simple

I watched Martin Odersky talk, as he recommended himself in the scala course, and I am very curious about one aspect of it

var x = 0 async { x = x + 1 } async { x = x * 2 } 

So, I get that it can give 2 if the first statement is executed first, and then the second:

 x = 0; x = x + 1; x = x * 2; // this will be x = 2 

I get how it can give 1:

 x = 0; x = x * 2; x = x + 1 // this will be x = 1 

However, how can this lead to 0? Is it possible that the statement is not executed at all?

Sorry for such a simple question, but I really got stuck in it

+6
source share
2 answers

You need to think about alternating execution. Remember that the CPU must read the x value before it can process it. So imagine the following:

  • Topic 1 reads x (read 0)
  • Topic 2 reads x (reading 0)
  • Topic 1 records x + 1 (record 1)
  • Thread 2 writes x * 2 (entry 0)
+9
source

I know this has already been answered, but perhaps this is still useful:

Think of it as a sequence of atomic operations. A processor performs one atom operation at a time.

Here we have the following:

  • Read x
  • Burn x
  • Add 1
  • Multiply 2

In this order "within oneself" the following two sequences are guaranteed:

  • Read x, add 1, write x
  • Read x, Multiply 2, Write x

However, if you execute them in parallel, the execution time of each atomic operation relative to any other atomic operation in a different sequence is random, that is, these two sequences alternate.

One possible execution order would be 0, which is given by Paul Butcher

Here is an illustration I found on the Internet:

enter image description here

Each blue / purple block is one atomic operation, you can see how you can have different results based on the block order

To solve this problem, you can use the synchronized keyword

I understand that if you mark two blocks of code (for example, two methods) with synchronization inside the same object, then each block will own a lock on this object during its execution, so that the other block cannot be executed while the first one still not finished. However, if you have two synchronized blocks in two different objects, they can be executed in parallel.

+5
source

All Articles