Location>code7788 >text

Interviewer: can a single core server be unlocked?

Popularity:57 ℃/2024-09-19 11:20:57

Today a student asked Lei a question, which probably means "Can a single-core server be unlocked?", I find it very interesting, so I will discuss it with you here:

1. Answers to questions

Let's start with my understanding.Single-core servers still need to be locked

That's because inSingle-core servers also have thread switching, if you don't add locks, then after thread switching, another thread can access the shared variables that have not been operated by other threads, which can lead to data overwriting problems with the operated shared variablesSo is the need for locks.

For example, in the following case, both thread T1 and thread T2 have to perform i++ operation, and the initial value of i is 0, so the correct execution result should be 2. However, if you don't add a lock, even under a single-core server, it will cause data overwriting problems, and the final execution result will be 1. The specific execution flow is as follows:

2. Analysis of causes

Because i++ is not an atomic operation, it is executed in 3 steps:

  1. Queries the value of i.
  2. Perform the i+1 modification operation.
  3. Assign the result to the i variable.

If it is a locking operation, then the threads can be executed one by one, first one thread first modifies i to 1, and then another thread modifies the result to 2 based on it again.

But if you don't add a lock, then it leads to the following problem:

Thread 1 Thread 2
t1 Reads the value of i as 0
t2 Reads the value of i as 0
t3 Perform a +1 operation to change i to 1
t4 Assign the result 1 to the i variable
t5 Perform a +1 operation to change i to 1
t6 Assign the result 1 to the i variable

As can be seen from the execution process described above, theEven on a single-core service, the problem of thread switching can still occur. And thread switching can lead to data overwriting problems, which is a thread-safety issue, so single-core servers also need locks

Post-lesson Reflections

What are some other means of ensuring thread safety besides locking mechanisms?

This article has been included in my interview mini-site, which contains modules such as Redis, JVM, Concurrency, Concurrency, MySQL, Spring, Spring MVC, Spring Boot, Spring Cloud, MyBatis, Design Patterns, Message Queuing and more.