java - A question about i++
phpcn_u1582
phpcn_u1582 2017-05-17 10:00:27
0
2
562

Use 2 threads to increment i=1 (i), and each thread executes it 100 times. What are the possible maximum and minimum values? Please give explanation

Also ask, is i atomic?

phpcn_u1582
phpcn_u1582

reply all(2)
洪涛

The minimum can be 3, which is +2, and the maximum can be 201, which is +200. . . . Why doesn't i start from 0. . .

A cycle process is:

  1. Read data from memory to register

  2. Register value++

  3. Write data back to memory

A thread may be interrupted in any of these three steps. The case of 3 is:
The first thread reads the data 1, then is suspended, and the register value is saved to another place. 1,然后被挂起,寄存器的值被保存到另一个地方。
第二个线程,持续执行了 99 次(此时,内存中的值为 100),然后被挂起。
第一个线程被唤醒,恢复寄存器的 1 +1 之后 (=2)被写回内存,该线程被挂起
第二个线程从内存读取2到寄存器之后被挂起
第一个全部执行完,把值写回内存
唤起第二个线程,恢复寄存器中的2The second thread continued to execute 99 times (at this time, the value in the memory was 100), and then was suspended.

The first thread is awakened, and after the 1 +1 of the recovery register (=2) is written back to the memory, the thread is suspended3The first The two threads read 2 from the memory into the register and are suspended. The first one is fully executed and writes the value back to the memory.

Avokes the second thread and restores the value in the register. 2, write back 3 after completing the last loop +1

So the end result is

. . . .

🎜I haven’t thought of a smaller scheduling method yet. . . 🎜 🎜The maximum value does not need to be explained too much. . . . 🎜
Ty80

The minimum value is 2 and the maximum value is 200.
2 means that both threads modify the data in the CPU cache, and in the end the memory is only refreshed once.
200 means that the two threads read and modify alternately without competing with each other.
We have all asked about the maximum and minimum values, but naturally they are not atomic.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!